import { Vue } from 'vue-property-decorator';
import set from 'lodash/set';
import omit from 'lodash/omit';
import cloneDeep from 'lodash/cloneDeep';
import { CardNeedToUpdateType } from '@constants/models/Card';
import { GetterTree, MutationTree } from 'vuex';

interface State {
  cards: Record<string, string>;
  models: Record<string, string>;
  schemas: Record<string, string>;
  needToUpdate: CardNeedToUpdateType;
  userTasks: Record<string, string>;
  statement: {
    id: string;
  };
}

export const state: State = {
  cards: {}, // Хранилище всех компонентов карточек
  models: {}, // Хранилище всех моделей карточек
  schemas: {}, // Хранилище всех схем карточек
  needToUpdate: CardNeedToUpdateType.FALSE, // Флаг, указывающий на необходимость обновления по его типу
  userTasks: {}, // Хранилище всех пользовательских задач карточек
  // todo refactor
  statement: {
    id: '316cd059-b801-4346-8956-fededd7da807',
  }, // Хранилище хардкода для заявлений
};

export const getters: GetterTree<State, State> = {
  cards(state) {
    return state.cards;
  },
  models(state) {
    return state.models;
  },
  needToUpdate(state) {
    return state.needToUpdate;
  },
  userTasks(state) {
    return state.userTasks;
  },
  getSchemaByPath: (state) => (path: string) => {
    return state.schemas[path] ?? {};
  },
};

// https://localhost:8080/microws/cards/statements/0b9f1098-9f87-454c-bd42-8c83ea2b0ae2?components=test-basic,test-tab

export const mutations: MutationTree<State> = {
  addCard(state, { card, name, path }) {
    const cards = set(state.cards, `[${path}][${name}]`, card);

    state.cards = cloneDeep(cards);
  },
  addModel(state, { model, path }) {
    const models = set(state.models, `[${path}]`, model);

    state.models = cloneDeep(models);
  },
  addUserTask(state, { path, userTask }) {
    const userTasks = set(state.userTasks, `[${path}]`, userTask);

    state.userTasks = cloneDeep(userTasks);
  },
  addSchema(state, { schema, path }) {
    Vue.set(state.schemas, path, schema);
  },
  cards(state, cards) {
    state.cards = cloneDeep(cards);
  },
  models(state, models) {
    state.models = cloneDeep(models);
  },
  needToUpdate(state, needToUpdate) {
    state.needToUpdate = needToUpdate;
  },
  userTasks(state, userTasks) {
    state.userTasks = cloneDeep(userTasks);
  },
  removeCard(state, { path }) {
    const cards = omit(state.cards, path);

    state.cards = cloneDeep(cards);
  },
  removeModel(state, { path }) {
    const models = omit(state.models, path);

    state.models = cloneDeep(models);
  },
  removeSchema(state, { path }) {
    Vue.delete(state.schemas, path);
  },
  removeUserTask(state, { path }) {
    const models = omit(state.models, path);

    state.models = cloneDeep(models);
  },
};

export const actions = {};
