import { Store } from "@/types";

let _inited = false;

// for dev
const _store = {
  globalMask: false,
  env: {
    loginName: "",
    password: "",
    server: { host: "", name: "" },
    user: {},
  },
  config: JSON.parse(JSON.stringify(window.electron.config)) || {},
  pageInputs: {},
} as Store;

// for dev
Object.assign(_store, JSON.parse(window.localStorage.getItem("store") || "{}"));

const handler = function () {
  return {
    // @ts-ignore
    set(obj, prop, value) {
      // console.log("set", obj, prop, value);
      // @ts-ignore
      obj[prop] = value;
      window.localStorage.setItem("store", JSON.stringify(_store));
      return true;
    },
    // @ts-ignore
    get(obj, prop) {
      // console.log("get", obj, prop);
      if (!_inited) {
        Object.assign(
          _store,
          JSON.parse(window.localStorage.getItem("store") || "{}")
        );
        _inited = true;
      }
      if (
        ["[object Object]", "[object Array]"].indexOf(
          Object.prototype.toString.call(obj[prop])
        ) > -1
      ) {
        return new Proxy(obj[prop], handler());
      }
      // @ts-ignore
      return obj[prop];
    },
  };
};
const store = new Proxy(_store, handler()) as Store;

export { store };

// @ts-ignore
window.store = store;
