import { MutationTree } from 'vuex'
import { State } from './index'

export enum MutationTypes {
  addDefs = 'addDefs',
  removeDefs = 'removeDefs',
  editDefs = 'editDefs'
}

interface DefsMap {
  key: string
  defs: any
}

export type Mutations<S = State> = {
  [MutationTypes.addDefs](state: S, defs_map: DefsMap): void
  [MutationTypes.removeDefs](state: S, defs_map: DefsMap): void
  [MutationTypes.editDefs](state: S, defs_map: DefsMap, key: string): void
}

export const mutations: MutationTree<State> & Mutations = {
  [MutationTypes.addDefs](state: State, defs_map: DefsMap) {
    if (defs_map.key && defs_map.defs)
      state.main.set(defs_map.key, defs_map.defs)
  },
  [MutationTypes.removeDefs](state: State, defs_map: DefsMap) {
    if (defs_map.key && defs_map.defs) {
      const defs = state.main.get(defs_map.key)
      defs.splice(defs.indexOf(defs_map.defs), 1)
      state.main.set(defs_map.key, defs)
    }
  },
  [MutationTypes.editDefs](state: State, defs_map: DefsMap) {
    if (defs_map.key && defs_map.defs) {
      const new_defs = [] as unknown as any
      const defs = state.main.get(defs_map.key)
      const key = defs_map.defs.id
      defs.forEach((it: any) => {
        if (it.id === key)
          new_defs.push(defs)
        else
          new_defs.push(it)
      })
      state.main.set(defs_map.key, new_defs)
    }
  },
}
