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

export enum MutationTypes {
  addCheck = 'addCheck',
  removeCheck = 'removeCheck',
  editCheck = 'editCheck'
}

interface CheckMap {
  key: string
  check: any
}

export type Mutations<S = State> = {
  [MutationTypes.addCheck](state: S, check_map: CheckMap): void
  [MutationTypes.removeCheck](state: S, check_map: CheckMap): void
  [MutationTypes.editCheck](state: S, check_map: CheckMap, key: string): void
}

export const mutations: MutationTree<State> & Mutations = {
  [MutationTypes.addCheck](state: State, check_map: CheckMap) {
    if (check_map.key && check_map.check)
      state.check.set(check_map.key, check_map.check)
  },
  [MutationTypes.removeCheck](state: State, check_map: CheckMap) {
    if (check_map.key && check_map.check) {
      const check = state.check.get(check_map.key)
      check.splice(check.indexOf(check_map.check), 1)
      state.check.set(check_map.key, check)
    }
  },
  [MutationTypes.editCheck](state: State, check_map: CheckMap) {
    if (check_map.key && check_map.check) {
      const new_check = [] as unknown as any
      const check = state.check.get(check_map.key)
      const key = check_map.check.id
      check.forEach((it: any) => {
        if (it.id === key)
          new_check.push(check)
        else
          new_check.push(it)
      })
      state.check.set(check_map.key, new_check)
    }
  },
}
