import { MutationTree } from 'vuex'
import { State } from './index'
import { AppData } from '~/store/types'

export enum MutationTypes {
  addData = 'addData',
  removeData = 'removeData',
  editData = 'editData'
}

interface DataMap {
  key: string
  data: any
}

export type Mutations<S = State> = {
  [MutationTypes.addData](state: S, data_map: DataMap): void
  [MutationTypes.removeData](state: S, data_map: DataMap): void
  [MutationTypes.editData](state: S, data_map: DataMap, key: string): void
}

export const mutations: MutationTree<State> & Mutations = {
  [MutationTypes.addData](state: State, data_map: DataMap) {
    if (data_map.key && data_map.data)
      state.data.set(data_map.key, data_map.data)
  },
  [MutationTypes.removeData](state: State, data_map: DataMap) {
    if (data_map.key && data_map.data) {
      const data = state.data.get(data_map.key)
      data.splice(data.indexOf(data_map.data), 1)
      state.data.set(data_map.key, data)
    }
  },
  [MutationTypes.editData](state: State, data_map: DataMap) {
    if (data_map.key && data_map.data) {
      const new_data = [] as unknown as any
      const data = state.data.get(data_map.key)
      const key = data_map.data.id
      data.forEach((it: any) => {
        if (it.id === key)
          new_data.push(data)
        else
          new_data.push(it)
      })
      state.data.set(data_map.key, new_data)
    }
  },
}
