// file includes helper methods used by the Vue instance
import Vue from "vue";
import store from "@/store";
import router from "@/router";
import { axiosCacheInstance } from "@/plugins/axios";
function parseJSON(string: string) {
  try {
    return JSON.parse(string);
  } catch (e) {
    return string;
  }
}

export default {
  /**
   * Get the user data if he is logged ( checking the token on the local storage )
   */
  fetchUserIfExists: () => {
    return new Promise<void>((resolve) => {
      if (store.getters.getToken) {
        store
          .dispatch("fetchUser")
          .catch(() => {
            // remove the token if it is expired
            localStorage.removeItem("token");
            // store.dispatch('fetchMessages', document.documentElement.lang)
            // .then(() => {
            resolve();
            // })
          })
          .then(() => {
            // store.dispatch('fetchMessages', store.getters.getUser.lang)
            // .then(() => {
            resolve();
            // })
          });
      } else {
        // set the locale
        store.commit("setUser", null);
        resolve();
      }
    });
  },
  /**
   * Fetch the app messages based on the locale
   */
  fetchMessages() {
    if (store.getters.getSettings.enableLangSwitcher) {
      axiosCacheInstance
        .get("/api/languages")
        .then((res: { data: any }) => {
          store.commit("setAvailableLanguages", res.data);
        })
        .then(() => {
          if (localStorage.getItem("pref-locale")) {
            store.dispatch(
              "fetchMessages",
              localStorage.getItem("pref-locale")
            );
          } else {
            store.dispatch("fetchMessages", document.documentElement.lang);
          }
        });
    } else {
      if (localStorage.getItem("pref-locale")) {
        store.dispatch("fetchMessages", localStorage.getItem("pref-locale"));
      } else {
        store.dispatch("fetchMessages", document.documentElement.lang);
      }
    }
  },
  /**
   * Set the setting values on the app.
   */

  updateSettings: () => {
    // @ts-ignore
    if (window.Settings) {
      const settings = {};
      // @ts-ignore
      window.Settings.forEach(
        (element: { key: string | number; value: string }) => {
          // @ts-ignore
          settings[element.key] =
            element.value == "0"
              ? false
              : element.value == "1"
              ? true
              : parseJSON(element.value);
        }
      );
      store.commit("setSettings", settings);
    }
  },
  setTheme: () => {
    return new Promise((resolve, rej) => {
      if (store.getters.getSettings) {
        var url = "/api/theme";
        // preview section
        if (localStorage.getItem("current_theme")) {
          url = url + "/" + localStorage.getItem("current_theme");
        }
        axiosCacheInstance.get(url).then((res) => {
          store.commit("setTheme", res.data);
          resolve(true);
        });
      } else {
        rej();
      }
    });
  },
  /**
   * Confirm dialog: if the user wants to proceed to login or not
   */
  loginOrCancel: () => {
    return new Promise((res, rej) => {
      // @ts-ignore
      Vue.$confirm({
        message: `You need to login to your account`,
        button: {
          no: "Cancel",
          yes: "Login",
        },
        callback: (confirm: any) => {
          if (confirm) {
            res(router.push({ name: "login" }));
          } else {
            rej();
          }
        },
      });
    });
  },
};
