import "es6-promise/auto";
import { Module } from "vuex";
import {
  makeFetch,
  PaginationResponse,
} from "ChillMainAssets/lib/api/apiMethods";
import {
  AccompanyingCourse,
  Alert,
  Evaluation,
  Warning,
  Workflow,
  WorflowCc,
  Notification,
} from "ChillPersonAssets/types";
import { RootState } from "..";
import { HomepageTabs } from "ChillMainAssets/types";

export interface TasksState {
  warning: PaginationResponse<Warning>;
  alert: PaginationResponse<Alert>;
}

export interface State {
  evaluations: PaginationResponse<Evaluation>;
  tasks: TasksState;
  accompanyingCourses: PaginationResponse<AccompanyingCourse>;
  notifications: PaginationResponse<Notification>;
  workflows: PaginationResponse<Workflow>;
  workflowsCc: PaginationResponse<WorflowCc>;
  errorMsg: unknown[];
  loading: boolean;
  ticketsLoading: boolean;
}

export const moduleHomepage: Module<State, RootState> = {
  state: {
    evaluations: {
      count: 0,
    } as PaginationResponse<Evaluation>,
    tasks: {
      warning: {
        count: 0,
      } as PaginationResponse<Warning>,
      alert: {
        count: 0,
      } as PaginationResponse<Alert>,
    },
    accompanyingCourses: {
      count: 0,
    } as PaginationResponse<AccompanyingCourse>,
    notifications: {
      count: 0,
    } as PaginationResponse<Notification>,
    workflows: {
      count: 0,
    } as PaginationResponse<Workflow>,
    workflowsCc: {
      count: 0,
    } as PaginationResponse<WorflowCc>,
    ticketsLoading: false,
    errorMsg: [],
    loading: false,
  },
  getters: {
    isTicketLoading: (state) => {
      return state.ticketsLoading;
    },
    isEvaluationsLoaded(state) {
      return Array.isArray(state.evaluations.results);
    },
    isTasksWarningLoaded(state) {
      return Array.isArray(state.tasks.warning.results);
    },
    isTasksAlertLoaded(state) {
      return Array.isArray(state.tasks.alert.results);
    },
    isAccompanyingCoursesLoaded(state) {
      return Array.isArray(state.accompanyingCourses.results);
    },
    isNotificationsLoaded(state) {
      return Array.isArray(state.notifications.results);
    },
    isWorkflowsLoaded(state) {
      return Array.isArray(state.workflows.results);
    },
  },
  mutations: {
    addEvaluations(state, evaluations) {
      state.evaluations = evaluations;
    },
    addTasksWarning(state, tasks) {
      state.tasks.warning = tasks;
    },
    addTasksAlert(state, tasks) {
      state.tasks.alert = tasks;
    },
    addCourses(state, courses) {
      state.accompanyingCourses = courses;
    },
    addNotifications(state, notifications) {
      state.notifications = notifications;
    },
    addWorkflows(state, workflows) {
      state.workflows = workflows;
    },
    addWorkflowsCc(state, workflows) {
      state.workflowsCc = workflows;
    },
    setLoading(state, bool) {
      state.loading = bool;
    },
    setTicketsLoading(state, bool) {
      state.ticketsLoading = bool;
    },
    catchError(state, error) {
      state.errorMsg.push(error);
    },
  },
  actions: {
    async getByTab({ commit, getters, dispatch }, { tab, param }) {
      switch (tab) {
        case HomepageTabs.MyTickets:
          if (!getters.isTicketsLoaded) {
            commit("setTicketsLoading", true);
            // Utilise l'action du module ticket_list
            await dispatch(
              "fetchTicketList",
              { byAddresseeToMe: true, byCurrentState: "open" },
              { root: true },
            );

            commit("setTicketsLoading", false);
          }
          break;
        case HomepageTabs.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 HomepageTabs.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 HomepageTabs.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 HomepageTabs.MyNotifications:
          if (!getters.isNotificationsLoaded) {
            commit("setLoading", true);
            const url = `/api/1.0/main/notification/my/unread${"?" + param}`;

            makeFetch("GET", url)
              .then((response) => {
                commit("addNotifications", response);
                commit("setLoading", false);
              })
              .catch((error) => {
                commit("catchError", error);
                throw error;
              });
          }
          break;
        case HomepageTabs.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;
      }
    },
  },
};
