import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";

const MaxLogLength = 100;

Vue.use(Vuex);

//reset all local settings via url
//localhost:8080/login?reset
if (window.location.search) {
  var searchParams = new URLSearchParams(window.location.search);
  if (searchParams.has("reset")) {
    localStorage.removeItem("AyaNova");
    console.log("LOCAL SETTINGS RESET");
  }
}

export default new Vuex.Store({
  plugins: [createPersistedState({ key: "AyaNova" })],
  state: {
    lastClientVersion: "",
    authenticated: false,
    apiToken: "-",
    downloadToken: "-",
    l: false, //license lockout flag
    tfaEnabled: undefined,
    customerRights: {},
    userId: 0,
    userName: "NOT AUTHENTICATED",
    roles: 0,
    userType: 0,
    homePage: undefined,
    translationText: {},
    enums: {}, //all enum values with translated text to match stored as key
    userOptions: {
      languageOverride: "en-US",
      timeZoneOverride: null, //use browser tz by default
      currencyName: "USD",
      hour12: true,
      uiColor: "#000000ff",
      emailAddress: null,
      mapUrlTemplate: null
    },
    globalSettings: {},
    navItems: [],
    logArray: [],
    formSettings: {}, //this is the settings on forms that survive a refresh like grid number of items to show etc
    formCustomTemplate: {}, //this is the custom fields settings for forms,
    darkMode: false,
    nativeDateTimeInput: false,
    knownPassword: false,
    newNotificationCount: 0
  },
  getters: {
    /* User types:
      Service = 1,
      NotService = 2,
      Customer = 3,
      HeadOffice = 4,        
      ServiceContractor = 5
    */
    isCustomerUser: state => {
      return state.userType == 3 || state.userType == 4;
    },
    isSubContractorUser: state => {
      return state.userType == 5;
    },
    isScheduleableUser: state => {
      return state.userType == 1 || state.userType == 5;
    },
    canSubscribeToNotifications: state => {
      switch (state.userType) {
        case 1:
        case 2:
          return true;
        case 3:
        case 4:
          //customer / headoffice and some notifications are enabled for them
          return (
            state.customerRights.notifyServiceImminent == true ||
            state.customerRights.notifyCSRAccepted == true ||
            state.customerRights.notifyCSRRejected == true ||
            state.customerRights.notifyWOCompleted == true ||
            state.customerRights.notifyWOCreated == true
          );
        case 5: //subcontractor for now no notification subscriptions available
          return false;
      }
      return false;
    },
    isSuperUser: state => {
      return state.userId === 1;
    }
  },
  mutations: {
    setLastClientVersion(state, data) {
      state.lastClientVersion = data;
    },
    login(state, data) {
      // mutate state
      state.authenticated = data.authenticated;
      state.userId = data.userId;
      state.roles = data.roles;
      state.apiToken = data.apiToken;
      state.userName = data.userName;
      state.userType = data.userType;
      state.downloadToken = data.dlt;
      state.l = data.l;
      state.tfaEnabled = data.tfaEnabled;
      if (data.customerRights) {
        state.customerRights = data.customerRights;
      }
    },
    logout(state) {
      //Things that are reset on logout
      state.apiToken = "-";
      state.downloadToken = "-";
      state.l = false;
      state.tfaEnabled = undefined;
      state.customerRights = {};
      state.authenticated = false;
      state.userId = 0;
      state.userName = "NOT AUTHENTICATED";
      state.roles = 0;
      state.userType = 0;
      state.homePage = undefined;
      state.navItems = [];
      state.translationText = {};
      state.enums = {};
      state.formCustomTemplate = {};
      state.userOptions.languageOverride = "en-US";
      state.userOptions.timeZoneOverride = null;
      state.userOptions.currencyName = "USD";
      state.userOptions.hour12 = true;
      //state.userOptions.uiColor = "#000000ff";
      state.userOptions.emailAddress = null;
      state.userOptions.mapUrlTemplate = null;
      state.globalSettings = {};
      state.knownPassword = false;
      state.newNotificationCount = 0;
    },
    addNavItem(state, data) {
      state.navItems.push(data);
    },
    setTranslationText(state, data) {
      state.translationText[data.key] = data.value;
    },
    setFormCustomTemplateItem(state, data) {
      state.formCustomTemplate[data.formKey + "_concurrencyToken"] =
        data.concurrency;
      state.formCustomTemplate[data.formKey] = data.value;
    },
    setUserOptions(state, data) {
      // mutate state
      state.userOptions.languageOverride = data.languageOverride;
      state.userOptions.currencyName = data.currencyName;
      state.userOptions.hour12 = data.hour12;
      state.userOptions.timeZoneOverride = data.timeZoneOverride;
      state.userOptions.emailAddress = data.emailAddress;
      //state.userOptions.uiColor = data.uiColor;
      state.userOptions.mapUrlTemplate = data.mapUrlTemplate;
    },
    setGlobalSettings(state, data) {
      // mutate state
      state.globalSettings = data;
    },
    setEnum(state, data) {
      state.enums[data.enumKey] = data.items;
    },
    logItem(state, msg) {
      msg = new Date().toLocaleString("sv-SE") + "|" + msg;
      state.logArray.push(msg);
      if (state.logArray.length > MaxLogLength) {
        //remove beginning elements
        state.logArray = state.logArray.slice(
          state.logArray.length - MaxLogLength
        );
      }
    },
    clearAllFormSettings(state) {
      state.formSettings = {};
    },
    setFormSettings(state, data) {
      state.formSettings[data.formKey] = data.formSettings;
    },
    clearFormSettings(state, formKey) {
      delete state.formSettings[formKey];
    },
    setHomePage(state, data) {
      state.homePage = data;
    },
    setDarkMode(state, data) {
      state.darkMode = data;
    },
    setNativeDateTimeInput(state, data) {
      state.nativeDateTimeInput = data;
    },
    setKnownPassword(state, data) {
      state.knownPassword = data;
    },
    setNewNotificationCount(state, data) {
      state.newNotificationCount = data;
    },
    setTfaEnabled(state, data) {
      state.tfaEnabled = data;
    }
  },
  actions: {}
});
