import { DEL_ITEM, REP_LIST, CHANGE_PAGING, UPDATE_ITEM } from "./actionType"

const delArrayItem = <T>(arr: Array<T>, item: T) => {
  let cArr = [...arr]
  cArr.splice(arr.indexOf(item), 1)
  return cArr
}

export function reducer<T>(state: State<T>, action: Action): State<T> {
  let cstate
  switch (action.type) {
    case DEL_ITEM:
      cstate = {
        ...state,
        list: delArrayItem(state.list, action.plyload)
      }
      break;
    case CHANGE_PAGING:  
      cstate = {
        ...state,
        paging: action.plyload
      }
      break
    case REP_LIST: {
      cstate = {
        ...state,
        list: action.plyload
      }
      break
    }
    case UPDATE_ITEM: {
      cstate = {...state, list: state.list}
      let index = cstate.list.indexOf(action.plyload.oldItem)
      cstate.list[index] = action.plyload.newItem
      break;
    }
    default: {
      cstate = state
    }
  }

  sessionStorage.setItem('state', JSON.stringify(cstate))
  return cstate
}
