import { HistoryRecord } from '../store/types'
import * as types from '../constants/history'

export interface HistoryState {
  records: HistoryRecord[]
  loading: boolean
  error: string | null
}

const initialState: HistoryState = {
  records: [],
  loading: false,
  error: null
}

export default function historyReducer(state = initialState, action: any): HistoryState {
  switch (action.type) {
    case types.LOAD_RECORDS_REQUEST:
    case types.ADD_RECORD_REQUEST:
    case types.UPDATE_RECORD_REQUEST:
    case types.DELETE_RECORD_REQUEST:
    case types.CLEAR_RECORDS_REQUEST:
      return {
        ...state,
        loading: true,
        error: null
      }

    case types.LOAD_RECORDS_SUCCESS:
      return {
        ...state,
        loading: false,
        records: action.payload,
        error: null
      }

    case types.ADD_RECORD_SUCCESS:
      return {
        ...state,
        loading: false,
        records: [action.payload, ...state.records],
        error: null
      }

    case types.UPDATE_RECORD_SUCCESS:
      return {
        ...state,
        loading: false,
        records: state.records.map(record =>
          record.id === action.payload.id ? action.payload : record
        ),
        error: null
      }

    case types.DELETE_RECORD_SUCCESS:
      return {
        ...state,
        loading: false,
        records: state.records.filter(record => record.id !== action.payload),
        error: null
      }

    case types.CLEAR_RECORDS_SUCCESS:
      return {
        ...state,
        loading: false,
        records: [],
        error: null
      }

    case types.LOAD_RECORDS_FAILURE:
    case types.ADD_RECORD_FAILURE:
    case types.UPDATE_RECORD_FAILURE:
    case types.DELETE_RECORD_FAILURE:
    case types.CLEAR_RECORDS_FAILURE:
      return {
        ...state,
        loading: false,
        error: action.payload
      }

    case types.CLEAR_ERROR:
      return {
        ...state,
        error: null
      }

    default:
      return state
  }
}
