import {
  projektojQuery,
  universoProjektojProjektoKategorioQuery,
  universoProjektojProjektoStatusoQuery,
  universoProjektojProjektoTipoQuery
} from 'src/queries/queries';
import { addProjekto, forigoProjekto } from 'src/queries/mutations';
import { apollo } from 'src/boot/apollo';

export default {
  namespaced: true,
  state() {
    return {
      types: null,
      categories: null,
      statuses: null,
      edges: [],
      pageInfo: null,
      objId: null,
      needRefresh: false
    };
  },
  getters: {
    getProjektoj: (state) => {
      return {
        pageInfo: state.pageInfo,
        edges: state.edges.map((item) => item[1])
      };
    },
    getTipoj: (state) => (state.types ? state.types.tipo : null),
    getKategorioj: (state) =>
      state.categories ? state.categories.kategorio : null,
    getStatusoj: (state) => (state.statuses ? state.statuses.statuso : null)
  },

  mutations: {
    setProjektoj: (state, pload) => {
      let mapList;
      const { objId, payload } = pload;
      if (objId === state.objId && state.needRefresh === false) {
        mapList = new Map(state.edges);
      } else {
        mapList = new Map();
      }
      payload.projektoj.edges.forEach((item) => {
        mapList.set(item.node.uuid, item);
      });
      state.pageInfo = payload.projektoj.pageInfo;
      state.edges = Array.from(mapList);
      state.objId = objId;
      state.needRefresh = false;
    },
    setNeedRefresh(state) {
      state.needRefresh = true;
      state.pageInfo = null;
    },
    setTipoj: (state, payload) => (state.types = payload),
    setKategorioj: (state, payload) => (state.categories = payload),
    setStatusoj: (state, payload) => (state.statuses = payload),
    setAddProjekto(state, payload) {
      state.edges.unshift([payload.uuid, { node: payload }]);
      state.needRefresh = true;
      state.pageInfo = null;
      this.commit('tutaProjektoj/setNeedRefresh');
    },
    setDelProjekto(state, payload) {
      const mapList = new Map(state.edges);
      if (mapList.has(payload)) {
        mapList.delete(payload);
      }
      state.edges = Array.from(mapList);
      state.needRefresh = true;
      state.pageInfo = null;
      // this.commit('tutaProjektoj/setDelProjekto',payload)
      this.commit('tutaProjektoj/setNeedRefresh');
    }
  },
  actions: {
    fetchProjektoj({ commit }, payload) {
      const { komunumoId } = payload;
      this.dispatch('UIstore/showLoading');
      return apollo.default
        .query({
          query: projektojQuery,
          variables: payload,
          errorPolicy: 'all',
          fetchPolicy: 'network-only'
        })
        .then(({ data }) => {
          commit('setProjektoj', { objId: komunumoId, payload: data });
          this.dispatch('UIstore/hideLoading');
        })
        .catch(() => {
          this.dispatch('UIstore/hideLoading');
        });
    },

    fetchKategorioj({ commit }) {
      this.dispatch('UIstore/showLoading');
      return apollo.default
        .query({
          query: universoProjektojProjektoKategorioQuery,
          errorPolicy: 'all',
          fetchPolicy: 'network-only'
        })
        .then(({ data }) => {
          commit('setKategorioj', data);
          this.dispatch('UIstore/hideLoading');
        })
        .catch(() => {
          this.dispatch('UIstore/hideLoading');
        });
    },
    fetchStatusoj({ commit }) {
      this.dispatch('UIstore/showLoading');
      return apollo.default
        .query({
          query: universoProjektojProjektoStatusoQuery,
          errorPolicy: 'all',
          fetchPolicy: 'network-only'
        })
        .then(({ data }) => {
          commit('setStatusoj', data);
          this.dispatch('UIstore/hideLoading');
        })
        .catch(() => {
          this.dispatch('UIstore/hideLoading');
        });
    },
    fetchTipoj({ commit }) {
      this.dispatch('UIstore/showLoading');
      return apollo.default
        .query({
          query: universoProjektojProjektoTipoQuery,
          errorPolicy: 'all',
          fetchPolicy: 'network-only'
        })
        .then(({ data }) => {
          commit('setTipoj', data);
          this.dispatch('UIstore/hideLoading');
        })
        .catch(() => {
          this.dispatch('UIstore/hideLoading');
        });
    },
    refetchProjektoj({ commit }, payload) {
      this.dispatch('UIstore/showLoading');
      return apollo.default
        .query({
          query: projektojQuery,
          variables: payload,
          errorPolicy: 'all',
          fetchPolicy: 'network-only'
        })
        .then(({ data }) => {
          commit('setProjektoj', data);
          this.dispatch('UIstore/hideLoading');
        })
        .catch(() => {
          this.dispatch('UIstore/hideLoading');
        });
    },
    addProjektoj({ commit }, payload) {
      this.dispatch('UIstore/showLoading');
      return apollo.default
        .mutate({
          mutation: addProjekto,
          variables: payload,
          update: () => {
            // eslint-disable-next-line no-console
            console.log('Регистрируем проект');
          }
        })
        .then((data) => {
          this.dispatch('UIstore/hideLoading');
          if (data?.data?.redaktuUniversoProjektojProjekto?.status) {
            // eslint-disable-next-line no-console
            console.log(
              `Проект ${data.data.redaktuUniversoProjektojProjekto.universoProjekto?.uuid} успешно зарегистрирован.\nОтвет сервера: ${data.data.redaktuUniversoProjektojProjekto.message}`
            );
            commit(
              'setAddProjekto',
              data.data.redaktuUniversoProjektojProjekto.universoProjekto
            );
          } else {
            // eslint-disable-next-line no-console
            console.log(
              `Проект не зарегистрирован. \nОшибка: ${
                data?.data?.redaktuUniversoProjektojProjekto?.message ??
                'Неизвестно'
              }`
            );
          }
        })
        .catch((error) => {
          // eslint-disable-next-line no-console
          console.error(error);
          this.dispatch('UIstore/hideLoading');
        });
    },
    delProjekto({ commit }, { id }) {
      // eslint-disable-next-line no-console
      console.log(id);
      this.dispatch('UIstore/showLoading');
      return apollo.default
        .mutate({
          mutation: forigoProjekto,
          variables: { id, forigo: true },
          update: () => {
            // eslint-disable-next-line no-console
            console.log('Удаляем проект');
          }
        })
        .then((data) => {
          this.dispatch('UIstore/hideLoading');
          if (data?.data?.redaktuUniversoProjektojProjekto?.status) {
            // eslint-disable-next-line no-console
            console.log(
              `Проект ${id} успешно удален.\nОтвет сервера: ${data.data.redaktuUniversoProjektojProjekto.message}`
            );
            commit('setDelProjekto', id);
          } else {
            // eslint-disable-next-line no-console
            console.log(
              `Проект ${id} не удален. \nОшибка: ${
                data?.data?.redaktuUniversoProjektojProjekto?.message ??
                'Неизвестно'
              }`
            );
          }
        })
        .catch((error) => {
          this.dispatch('UIstore/hideLoading');
          // eslint-disable-next-line no-console
          console.error(error);
        });
    }
  }
};
