// @flow

import React from 'react';
import { View, Text, ListView } from 'react-native';
import { connect } from 'react-redux';
// For empty lists
import AlertMessage from '../Components/AlertMessage';
// Styles
import styles from './Styles/ListviewExampleStyle';

class ListviewExample extends React.Component {
  state: {
    dataSource: Object
  }

  constructor(props) {
    super(props);
    /* ***********************************************************
    * Teach datasource how to detect if rows are different
    * Make this function fast!  Perhaps something like:
    *   (r1, r2) => r1.id !== r2.id}
    *************************************************************/
    const rowHasChanged = (r1, r2) => r1 !== r2;

    // DataSource configured
    const ds = new ListView.DataSource({rowHasChanged});

    // Datasource is always in state
    this.state = {
      dataSource: ds.cloneWithRows(props.results),
    };
  }

  /* ***********************************************************
  * `_renderRow` function -How each cell/row should be rendered
  * It's our best practice to place a single component here:
  *
  * e.g.
    return <MyCustomCell title={rowData.title} description={rowData.description} />
  *************************************************************/
  _renderRow(searchTerm) {
    return (
      <View style={styles.row}>
        <Text style={styles.boldLabel}>{searchTerm}</Text>
      </View>
    );
  }

  /* ***********************************************************
  * If your datasource is driven by Redux, you'll need to
  * reset it when new data arrives.
  * DO NOT! place `cloneWithRows` inside of render, since render
  * is called very often, and should remain fast!  Just replace
  * state's datasource on newProps.
  *
  * e.g.
  *************************************************************/
  componentWillReceiveProps(newProps) {
    if (newProps.results) {
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(newProps.results),
      });
    }
  }

  // Used for friendly AlertMessage
  // returns true if the dataSource is empty
  _noRowData() {
    return this.state.dataSource.getRowCount() === 0;
  }

  render() {
    return (
      <View style={styles.container}>
        <AlertMessage title="Nothing to See Here, Move Along" show={this._noRowData()} />
        <ListView
          contentContainerStyle={styles.listContent}
          dataSource={this.state.dataSource}
          renderRow={this._renderRow}
          pageSize={15}
          enableEmptySections
        />
      </View>
    );
  }
}

const mapStateToProps = state => ({
  searchTerm: state.search.searchTerm,
  results: state.search.results,
});

export default connect(mapStateToProps)(ListviewExample);
