import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchDeals } from '../actions/index';
import DealSummary from './deal-summary';

class DealsList extends Component {

  componentWillMount() {
    console.log('call action creator to get list of deals');
    this.props.fetchDeals(this.props.category);
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.category !== this.props.category){
      this.props.fetchDeals(nextProps.category);
    }
  }

  renderDeals() {
    if (this.props.allDeals.length === 0) {
      return (
        <div>
          Could not find any deals on this category.
        </div>
      )
    }

    return (this.props.allDeals.map((deal) => {
      return (
        <DealSummary key={deal.id} id={deal.id} title={deal.title} category={deal.category} author={deal.author} summary={deal.summary} image={deal.picture} />
      );
    }));
  }

  render() {
    return (
      <div className="deals-list">
        {this.renderDeals()}
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    allDeals: state.deals.allDeals
  };
}

export default connect(mapStateToProps, { fetchDeals })(DealsList);
