const axios = require("axios");

import Vue from 'vue';
import Vuex from 'vuex';
import router from '../router'
//import modules from './modules';

Vue.use(Vuex);


axios.defaults.withCredentials = true; // * add cookies to axios
function updateAxiosHeader() {
  axios.defaults.headers.common['X-CSRFToken'] = (name => {
    var re = new RegExp(name + "=([^;]+)");
    var value = re.exec(document.cookie);
    return (value != null) ? unescape(value[1]) : null;
  })('csrftoken');
}
// ! À vérifier s'il y a un changement de token pendant l'éxécution de l'appli
updateAxiosHeader();

const DJANGO_API_BASE = process.env.VUE_APP_DJANGO_API_BASE;

export default new Vuex.Store({
  //  modules,
  state: {
    features: [],
    feature_types: [],
    status_choices: [],
    logged: false,
    user: false,
    project: null,
    projectMembers: null,
    projects: [],
    staticPages: null,
    SSO_SETTED: false,
    USER_LEVEL_PROJECTS: null
  },

  mutations: {
    SET_PROJECTS(state, projects) {
      state.projects = projects;
    },
    SET_PROJECT(state, project) {
      state.project = project;
    },
    SET_PROJECT_MEMBERS(state, projectMembers) {
      state.projectMembers = projectMembers;
    },
    SET_USER(state, payload) {
      state.user = payload;
    },
    SET_COOKIE(state, cookie) {
      state.cookie = cookie
    },
    SET_STATIC_PAGES(state, staticPages) {
      state.staticPages = staticPages
    },
    SET_SSO(state, SSO_SETTED) {
      state.SSO_SETTED = SSO_SETTED
    },
    SET_USER_LEVEL_PROJECTS(state, USER_LEVEL_PROJECTS) {
      state.USER_LEVEL_PROJECTS = USER_LEVEL_PROJECTS
    },
    SET_LOGGED(state, value) {
      state.logged = value
    }
  },

  getters: {
    project_types: state => {
      return state.projects.filter(projet => projet.is_project_type);
    }
  },

  actions: {
    async GET_ALL_PROJECTS({ commit }) {
      function parseDate(date) {
        let dateArr = date.split("/").reverse()
        return new Date(dateArr[0], dateArr[1] - 1, dateArr[2])
      }
      await axios
        .get(`${DJANGO_API_BASE}projects/`)
        .then((response) => {
          const orderedProjects = response.data.sort((a, b) => parseDate(b.created_on) - parseDate(a.created_on));
          commit("SET_PROJECTS", orderedProjects)
        })
        .catch((error) => {
          throw error;
        });
    },
    async GET_STATIC_PAGES({ commit }) {
      await axios
        .get(`${DJANGO_API_BASE}aide/`)
        .then((response) => (commit("SET_STATIC_PAGES", response.data)))
        .catch((error) => {
          throw error;
        });
    },
    LOGIN({ commit, dispatch }, payload) {
      if (payload.username && payload.password) {
        axios
          .post(`${DJANGO_API_BASE}login/`, {
            username: payload.username,
            password: payload.password,
          })
          .then((response) => {
            const routerHistory = router.options.routerHistory // * use store previous route to go back after login
            commit("SET_USER", response.data.user);
            router.push(routerHistory[routerHistory.length - 1] || "/")
            dispatch("GET_USER_LEVEL_PROJECTS");
          })
          .catch(() => {
            commit("SET_USER", false)
          });
      }
    },

    USER_INFO({ commit }) {
      axios
        .get(`${DJANGO_API_BASE}user_info/`)
        .then((response) => {
          const user = response.data.user;
          commit("SET_USER", user)
          window.localStorage.setItem("user", JSON.stringify(user))
        }) // todo: ajouter au localestorage
        .catch(() => {
          router.push({ name: "login" });
        });
    },

    LOGOUT({ commit }) { // ? logout dans django ?
      axios
        .get(`${DJANGO_API_BASE}logout/`)
        .then((response) => {
          console.log(response)
          commit("SET_USER", false) // ? better false or null
          commit("SET_USER_LEVEL_PROJECTS", null)
        })
        .catch((error) => {
          throw error
        });

    },

    GET_USER_LEVEL_PROJECTS({ commit }) {
      commit("SET_USER_LEVEL_PROJECTS", "Administrateur projet") // todo : use authentification)
      /* axios
        .get(`${DJANGO_API_BASE}user_level_project/`)
        .then((response) => (commit("SET_USER_LEVEL_PROJECTS", response.data)))
        .catch((error) => {
          throw error;
        }); */
    },
    GET_PROJECT({ commit }, project_slug) {
      axios
        .get(`${DJANGO_API_BASE}projet/${project_slug}/project`)
        .then((response) => commit("SET_PROJECT", response.data))
        .catch((error) => {
          throw error;
        });
    },
    GET_PROJECT_USER({ commit }, project_slug) {
      axios
        .get(`${DJANGO_API_BASE}projet/${project_slug}/utilisateurs`)
        .then((response) => (commit("SET_PROJECT_MEMBERS", response.data.members)))
        .catch((error) => {
          throw error;
        });
    },
    GET_COOKIE({ commit }, name) {
      let cookieValue = null;

      if (document.cookie && document.cookie !== "") {
        const cookies = document.cookie.split(";");
        for (let i = 0; i < cookies.length; i++) {
          const cookie = cookies[i].trim();

          // Does this cookie string begin with the name we want?
          if (cookie.substring(0, name.length + 1) === name + "=") {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));

            break;
          }
        }
      }
      commit("SET_COOKIE", cookieValue);
    },
  }

});