/** Screen for listing conversations **/
import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { FlatList, Image, Text, View } from 'react-native';
import { Button } from 'react-native-elements';
import { conversationListFetch } from '../../actions';
import ConversationItem from '../../components/lists/ConversationItem';
import Footer from '../../components/common/Footer';
import { Spacer, Spinner } from '../../components/common';
import colors from '../../config/colors.json';
import { strings } from '../../locales/i18n';

const LOGO = require('../../../assets/tagfer_brand_and_logo_512.png');

let conversationResults = [];

class ConversationList extends Component {
  static navigationOptions = ({ navigation }) => {
    return {
      title: strings('message.conversations_title'),
      headerLeft: (
        <Button
          icon={{
            name: 'settings',
            type: 'simple-line-icon',
            color: colors.middleGrey,
            size: 30
          }}
          onPress={() => navigation.navigate('DrawerOpen')}
          backgroundColor={colors.transparent}
        />
      )
    };
  }

  state = { loading: true, noItems: false };

  /**
  * Component Will Mount
  **/
  componentWillMount() {
    this.props.conversationListFetch();
  }

  /**
  * Component Did Mount
  **/
  componentDidMount() {
    this.setState({ loading: false });
  }

  /**
  * Component Will Receive Props
  **/
  componentWillReceiveProps(nextProps) {
    if (nextProps.conversations) {
      this.populateConversationResults(nextProps);
    }
    if (!_.isEqual(this.props.conversations, nextProps.conversations) || this.props.success) {
      this.setState({ loading: false });
      if (nextProps.conversations.length === 0) {
        this.setState({ noItems: true });
      }
    }
  }

  /**
  * Formats conversationResults for the FlatList
  **/
  populateConversationResults(nextProps) {
    nextProps.conversations.sort((a, b) => this.compare(a, b));
    conversationResults = nextProps.conversations;
  }

  /**
  * Used for sorting conversationResults based on fullName property
  **/
  compare(a, b) {
    if (a.fullName.toLowerCase() < b.fullName.toLowerCase()) {
      return -1;
    }
    if (a.fullName.toLowerCase() > b.fullName.toLowerCase()) {
      return 1;
    }
    return 0;
  }

  /**
  * Creates a unique key for each contact
  **/
  keyExtractor = (item) => {
    return `${item.uid}`;
  }

  /**
  * Renders each row of the list
  **/
  renderItem = ({ item }) => {
    return <ConversationItem {...this.props} item={item} />;
  }

  /**
  * Render method
  **/
  render() {
    if (this.state.loading) {
      return (
        <Spinner size="large" />
      );
    }

    if (this.state.noItems) {
      return (
        <View style={styles.noItemsViewStyle}>
          <Spacer />
          <Image
            source={LOGO}
            style={styles.logoStyle}
          />
          <Spacer space={45} />

          <Text style={styles.noItemsTextStyle}>
            {strings('message.noItems')}
          </Text>
          <View />
          <View style={styles.mainFooterStyle}>
            <Footer
              {...this.props}
              index={3}
            />
          </View>
        </View>
      );
    }

    return (
      <View style={{ flex: 1, backgroundColor: colors.white }}>
        <FlatList
          keyExtractor={this.keyExtractor}
          renderItem={this.renderItem}
          data={conversationResults}
        />
        <View style={styles.mainFooterStyle}>
          <Footer
            {...this.props}
            index={3}
          />
        </View>
      </View>
    );
  }
}

const styles = {
  noItemsViewStyle: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'flex-start',
    alignItems: 'center',
    backgroundColor: colors.white
  },
  logoStyle: {
    height: 200,
    width: 200,
    marginTop: 15,
    marginBottom: 15
  },
  noItemsTextStyle: {
    fontSize: 18,
    marginHorizontal: 15
  },
  mainFooterStyle: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    height: 60
  }
};

/**
* Map State To Props
**/
const mapStateToProps = state => {
  // converts conversation objects into conversation arrays
  const conversations = _.map(state.conversations, (val, uid) => {
      return { ...val, uid };
  });

  // Required for the avatar to load in the footer
  const {
    profileAvatarImg
  } = state.profileForm;

  const { success } = state.conversationStatus;

  return { conversations, profileAvatarImg, success };
};

export default connect(mapStateToProps, {
  conversationListFetch
})(ConversationList);
