const user = {
  state: {
    name: "",
    role: "",
    accessToken: "",
    schoolId: "",
    school: {},
  },
  mutations: {
    resolveAccessToken(state, token) {
      state.accessToken = token;
      localStorage.accessToken = token;
    },
    resolveName(state, name) {
      state.name = name;
      localStorage.name = name;
    },
    setAccessToken(state) {
      state.accessToken = localStorage.accessToken;
      state.schoolId = localStorage.schoolId;
    },
    resolveSchoolId(state, schoolId) {
      state.schoolId = schoolId;
      localStorage.schoolId = schoolId;
    },
    resolveRole(state, role) {
      state.role = role;
      localStorage.role = role;
    },
    setRole(state) {
      state.role = localStorage.role;
    },
    resolveSchool(state, school) {
      state.school = school;
      localStorage.school = school ? JSON.stringify(school) : undefined;
    },
    resolveEncryptToken() {
      if (localStorage.accessToken && localStorage.accessToken.length > 0) {
        let token_str = "";
        for (let i = localStorage.accessToken.length - 1; i >= 0; i--) {
          token_str += localStorage.accessToken.charAt(i);
        }
        token_str = "$" + token_str + "~";
        token_str = encodeURIComponent(token_str);
        localStorage.encryptToken = token_str;
      }
    },
    setName(state) {
      state.name = localStorage.name;
    },
  },
  actions: {
    initLocalUserStore({ commit }) {
      if (localStorage.name) commit("resolveName", localStorage.name);
      if (localStorage.role) commit("resolveRole", localStorage.role);
      commit("setAccessToken");
      if (localStorage.school !== "undefined" && localStorage.school) {
        commit("resolveSchool", JSON.parse(localStorage.school));
      }
    },
  },
};

export default user;
