import queryString from 'query-string';
import { getCurrentUrl } from '@/browser/tab';
import { indentifySetting } from '@/plugins/setting';
import { fetchExtensionInfo, fetchPlatformConfig } from '@/api/autoshopee/cms';
import {
  getBrowserName, getBrowserAgent, getPlatformInfo, getIpAddress, getHashProfileId, getFingerprintId,
} from '@/lib/get';

export const actions = {
  async AppIndentify({ commit }) {
    const browserIp = await getIpAddress();
    const browserOs = (await getPlatformInfo()).os;
    const profileId = await getHashProfileId(browserIp);
    const fingerprintId = await getFingerprintId();

    indentifySetting.fingerprintId.set(fingerprintId);
    indentifySetting.profileId.set(profileId);
    indentifySetting.browserAgent.set(getBrowserAgent());
    indentifySetting.browserName.set(getBrowserName());
    indentifySetting.browserIp.set(browserIp);
    indentifySetting.browserPlatform.set(browserOs);

    commit('SET_APP_INDENTIFY');
  },
  async FetchExtensionInfo({ commit }) {
    const extensionInfo = await fetchExtensionInfo();
    const platformConfig = await fetchPlatformConfig();

    commit('SET_APP_EXTENSION_INFO', extensionInfo);
    commit('SET_SHOP_PLATFORM_CONFIG', platformConfig);

    return {
      extensionInfo,
      platformConfig,
    };
  },
  async AppInitUrl({ commit, getters }) {
    if (getters.getUrlCurrent) {
      return getters.getUrlCurrent;
    }

    let url = await getCurrentUrl();

    const urlParser = queryString.parse(url);

    if (urlParser && urlParser.refUrl) {
      url = urlParser.refUrl;
    }

    if (!url) {
      return '';
    }

    commit('SET_URL_CURRENT', url);

    return url;
  },
  SetAppLoading({ commit }, value) {
    commit('SET_APP_LOADING', value);
  },
  SetMenuActive({ commit }, value) {
    commit('SET_MENU_ACTIVE', value);
  },
  SetAppTitle({ commit }, title) {
    document.title = title;
    commit('SET_APP_TITLE', title);
  },
};
