import { defineStore } from "pinia";
import { idbStore } from "dasmap/core/idbStore.js";
import { asfa } from "dasmap/core/asfa.js";

let setDataModels = function (payload) {
  let state = this;
  let key = payload[0];
  let data = payload[1];
  let persistent = payload[2];
  if (!state.dataModels) {
    state.dataModels = {};
  }
  state.dataModels[key] = data;
  state.dataId = key;
  //~ state.dataStatus[key] = true;

  if (key != "" && persistent == true && idbStore.db) {
    idbStore.put({ key: key, data: data });
  }
};

let setStatusData = function (payload) {
  let state = this;
  let key = payload[0];
  let status = payload[1];
  state.dataStatus[key] = status;
};

let setActiveData = function (payload) {
  let state = this;
  let key = payload[0];
  let n = payload[1];
  state.activeData = n >= 0 ? state.dataModels[key][n] : null;
};

let setUserIdentity = function (payload) {
  let state = this;
  state.userIdentity = payload;
  asfa.encode(JSON.stringify(state.userIdentity), function (_px) {
    //~ localStorage.setItem("_userIdentity" + btoa(asfa.baseUrl), btoa(_px));    
    asfa.setCookie("_userIdentity" + btoa(asfa.baseUrl), btoa(_px), asfa.xDays);
    localStorage.removeItem("_userIdentity" + btoa(asfa.baseUrl));
  });
};

let setDarkMode = function (payload) {
  let state = this;
  state.darkMode = payload;
  localStorage.setItem("_darkMode", JSON.stringify(state.darkMode));
};

let commit = function (act, payload) {
  let state = this;
  act = act.replace("apps/", "");
  state[act](payload);
};

let getUi = function () {
  let ui = false;
  let res = asfa.getCookie("_userIdentity" + btoa(asfa.baseUrl));
  if (!res) {
    res = localStorage.getItem("_userIdentity" + btoa(asfa.baseUrl));
  }
  if (res != null && (res + "").substr(0, 1) != "{") {
    let decrypted = asfa.hex2b(atob(res));
    let data = new TextDecoder("utf-8").decode(decrypted);
    ui = JSON.parse(data);
  }
  return ui;
};

export const useStore = defineStore("apps", {
  state: () => ({
    dataModels: {},
    activeData: false,
    userIdentity: getUi(),
    darkMode: JSON.parse(localStorage.getItem("_darkMode")) || false,
    dataId: 0,
    dataStatus: {},
  }),
  getters: {
    state: function () {
      return {
        apps: this,
      };
    },
  },
  actions: {
    setActiveData,
    setDarkMode,
    setDataModels,
    setStatusData,
    setUserIdentity,
    commit,
  },
});
