import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";
import _ from "./utils/libs/lodash.js";

const MaxLogLength = 100;

Vue.use(Vuex);

export default new Vuex.Store({
  plugins: [createPersistedState()],
  state: {
    authenticated: false,
    apiUrl: "",
    helpUrl: "",
    apiToken: "-",
    userId: 0,
    roles: 0,
    localeText: {},
    navItems: [],
    logArray: []
  },
  mutations: {
    login(state, data) {
      // mutate state
      state.authenticated = data.authenticated;
      state.userId = data.userId;
      state.roles = data.roles;
      state.apiToken = data.apiToken;
    },
    logout(state) {
      state.apiToken = "-";
      state.authenticated = false;
      state.userId = 0;
      state.roles = 0;
      state.navItems = [];
      state.localeText = {};
      state.apiUrl = "";
    },
    addNavItem(state, data) {
      state.navItems.push(data);
    },
    addLocaleText(state, data) {
      state.localeText[data.key] = data.value;
    },
    setAPIURL(state, data) {
      state.apiUrl = data;
    },
    setHelpURL(state, data) {
      state.helpUrl = data;
    },
    logItem(state, msg) {
      msg = Date.now() + "|" + msg;
      state.logArray.push(msg);
      if (state.logArray.length > MaxLogLength) {
        state.logArray = _.drop(
          state.logArray,
          state.logArray.length - MaxLogLength
        );
      }
    }
  },
  actions: {}
});
