import React from 'react';
import { connect } from 'react-redux';
import { liftActions } from './util';
import {
  counter,
  initialState,
  onIncrement,
  onDecrement,
  onReset,
  Counter
} from './Counter';

const onAddCounter = () => ({ 
  type: 'ADD_COUNTER' 
});

const onRemoveCounter = (id) => ({ 
  type: 'REMOVE_COUNTER', id 
});

export const counters = (state = [], action) => {
  switch (action.type) {
    case 'INCREMENT_COUNTER':
    case 'DECREMENT_COUNTER':
    case 'RESET_COUNTER':
      return state.map((c) => counter(c, action));
    case 'ADD_COUNTER':
      return [ ...state, initialState() ];
    case 'REMOVE_COUNTER':
      return state.filter((c) => c.id !== action.id);
    default:
      return state;
  }
};

const Counters = ({ counters, increment, decrement, reset, remove, add }) => (
  <div>
    <h1>Counters</h1>
    {counters.map((c) => 
      <Counter 
        key={c.id}
        id={c.id}
        count={c.count}
        reset={() => reset(c.id)}
        increment={() => increment(c.id)}
        decrement={() => decrement(c.id)}
        remove={() => remove(c.id)}
      />
    )}
    <button onClick={add}>{'Add a counter +'}</button>
  </div>
);

const bindCounterActions = (dispatch) => 
  liftActions(dispatch, {
    add: onAddCounter,
    remove: onRemoveCounter,
    increment: onIncrement,
    decrement: onDecrement,
    reset: onReset
  });

const mapStateToProps = (state) => ({
  counters: state.counters
});


export default connect(mapStateToProps, bindCounterActions)(Counters);
