import "es6-promise/auto";
import { createStore } from "vuex";
import { makeFetch } from "ChillMainAssets/lib/api/apiMethods";

const debug = process.env.NODE_ENV !== "production";

const isEmpty = (obj) => {
  return (
    obj &&
    Object.keys(obj).length <= 1 &&
    Object.getPrototypeOf(obj) === Object.prototype
  );
};

const store = createStore({
  strict: debug,
  state: {
    // works: {},
    evaluations: {},
    tasks: {
      warning: {},
      alert: {},
    },
    accompanyingCourses: {},
    notifications: {},
    workflows: {},
    workflowsCc: {},
    errorMsg: [],
    loading: false,
  },
  getters: {
    // isWorksLoaded(state) {
    //     return !isEmpty(state.works);
    // },
    isEvaluationsLoaded(state) {
      return !isEmpty(state.evaluations);
    },
    isTasksWarningLoaded(state) {
      return !isEmpty(state.tasks.warning);
    },
    isTasksAlertLoaded(state) {
      return !isEmpty(state.tasks.alert);
    },
    isAccompanyingCoursesLoaded(state) {
      return !isEmpty(state.accompanyingCourses);
    },
    isNotificationsLoaded(state) {
      return !isEmpty(state.notifications);
    },
    isWorkflowsLoaded(state) {
      return !isEmpty(state.workflows);
    },
    counter(state) {
      return {
        // works: state.works.count,
        evaluations: state.evaluations.count,
        tasksWarning: state.tasks.warning.count,
        tasksAlert: state.tasks.alert.count,
        accompanyingCourses: state.accompanyingCourses.count,
        notifications: state.notifications.count,
        workflows: state.workflows.count,
      };
    },
  },
  mutations: {
    // addWorks(state, works) {
    //     //console.log('addWorks', works);
    //     state.works = works;
    // },
    addEvaluations(state, evaluations) {
      //console.log('addEvaluations', evaluations);
      state.evaluations = evaluations;
    },
    addTasksWarning(state, tasks) {
      //console.log('addTasksWarning', tasks);
      state.tasks.warning = tasks;
    },
    addTasksAlert(state, tasks) {
      //console.log('addTasksAlert', tasks);
      state.tasks.alert = tasks;
    },
    addCourses(state, courses) {
      //console.log('addCourses', courses);
      state.accompanyingCourses = courses;
    },
    addNotifications(state, notifications) {
      //console.log('addNotifications', notifications);
      state.notifications = notifications;
    },
    addWorkflows(state, workflows) {
      state.workflows = workflows;
    },
    addWorkflowsCc(state, workflows) {
      state.workflowsCc = workflows;
    },
    setLoading(state, bool) {
      state.loading = bool;
    },
    catchError(state, error) {
      state.errorMsg.push(error);
    },
  },
  actions: {
    getByTab({ commit, getters }, { tab, param }) {
      switch (tab) {
        // case 'MyWorks':
        //     if (!getters.isWorksLoaded) {
        //         commit('setLoading', true);
        //         const url = `/api/1.0/person/accompanying-period/work/my-near-end${'?'+ param}`;
        //         makeFetch('GET', url)
        //             .then((response) => {
        //                 commit('addWorks', response);
        //                 commit('setLoading', false);
        //             })
        //             .catch((error) => {
        //                 commit('catchError', error);
        //                 throw error;
        //             })
        //         ;
        //     }
        //     break;
        case "MyEvaluations":
          if (!getters.isEvaluationsLoaded) {
            commit("setLoading", true);
            const url = `/api/1.0/person/accompanying-period/work/evaluation/my-near-end${"?" + param}`;
            makeFetch("GET", url)
              .then((response) => {
                commit("addEvaluations", response);
                commit("setLoading", false);
              })
              .catch((error) => {
                commit("catchError", error);
                throw error;
              });
          }
          break;
        case "MyTasks":
          if (!(getters.isTasksWarningLoaded && getters.isTasksAlertLoaded)) {
            commit("setLoading", true);
            const urlWarning = `/api/1.0/task/single-task/list/my?f[q]=&f[checkboxes][status][]=warning&f[checkboxes][states][]=new&f[checkboxes][states][]=in_progress${"&" + param}`,
              urlAlert = `/api/1.0/task/single-task/list/my?f[q]=&f[checkboxes][status][]=alert&f[checkboxes][states][]=new&f[checkboxes][states][]=in_progress${"&" + param}`;
            makeFetch("GET", urlWarning)
              .then((response) => {
                commit("addTasksWarning", response);
                commit("setLoading", false);
              })
              .catch((error) => {
                commit("catchError", error);
                throw error;
              });
            makeFetch("GET", urlAlert)
              .then((response) => {
                commit("addTasksAlert", response);
                commit("setLoading", false);
              })
              .catch((error) => {
                commit("catchError", error);
                throw error;
              });
          }
          break;
        case "MyAccompanyingCourses":
          if (!getters.isAccompanyingCoursesLoaded) {
            commit("setLoading", true);
            const url = `/api/1.0/person/accompanying-course/list/by-recent-attributions${"?" + param}`;
            makeFetch("GET", url)
              .then((response) => {
                commit("addCourses", response);
                commit("setLoading", false);
              })
              .catch((error) => {
                commit("catchError", error);
                throw error;
              });
          }
          break;
        case "MyNotifications":
          if (!getters.isNotificationsLoaded) {
            commit("setLoading", true);
            const url = `/api/1.0/main/notification/my/unread${"?" + param}`;
            makeFetch("GET", url)
              .then((response) => {
                console.log("notifications", response);
                commit("addNotifications", response);
                commit("setLoading", false);
              })
              .catch((error) => {
                commit("catchError", error);
                throw error;
              });
          }
          break;
        case "MyWorkflows":
          if (!getters.isWorflowsLoaded) {
            commit("setLoading", true);
            makeFetch("GET", "/api/1.0/main/workflow/my")
              .then((response) => {
                commit("addWorkflows", response);
                makeFetch("GET", "/api/1.0/main/workflow/my-cc")
                  .then((response) => {
                    commit("addWorkflowsCc", response);
                    commit("setLoading", false);
                  })
                  .catch((error) => {
                    commit("catchError", error);
                    throw error;
                  });
              })
              .catch((error) => {
                commit("catchError", error);
                throw error;
              });
          }
          break;
        default:
          throw "tab " + tab;
      }
    },
  },
});

export { store };
