import { httpNoAuth } from "@/plugins/axiosNoAuth";
import { VITE_CONFIG_FILE_SEVER_URL } from "@/constants/constants";
import { VCAM_LIST, REMOTE_APP_NAME } from "@/constants/constant-namelist";
import { decryptB } from "@/utils/utils";

interface ParsedBlackAppConfig {
  vCamList: string[];
  remoteApp: string[];
}

interface RawBlackAppConfig {
  vCamList: string;
  remoteApp: string;
}

interface MergedBlackAppConfig {
  vCamList: string[];
  remoteApp: string;
}

interface GetBlackAppConfig {
  (): Promise<MergedBlackAppConfig>;
  fetch?: Promise<MergedBlackAppConfig>;
}

/**
 * @description 获取配置的虚拟摄像头和远程软件黑名单
 */
export let getBlackAppConfig: GetBlackAppConfig = () => {
  if (getBlackAppConfig.fetch) {
    return getBlackAppConfig.fetch;
  }
  const fetch = httpNoAuth
    .get<string>(`${VITE_CONFIG_FILE_SEVER_URL}/oe_client/software.json`, {
      "axios-retry": { retries: 3 },
      noErrorMessage: true,
    })
    .then((response) => response.data)
    .catch(() => {
      getBlackAppConfig.fetch = void 0;
      return "";
    })
    .then(parseBlackAppConfig)
    .then(mergeBlackAppConfig)
    .then((result) => {
      if (getBlackAppConfig.fetch) {
        getBlackAppConfig = () => Promise.resolve(result);
      }
      return result;
    });
  getBlackAppConfig.fetch = fetch;
  return fetch;
};

function parseBlackAppConfig(str: string): ParsedBlackAppConfig {
  const result: ParsedBlackAppConfig = {
    vCamList: [],
    remoteApp: [],
  };
  try {
    if (typeof str === "string") {
      const s = str.slice(0, -32).split("").reverse().join("");
      if (s.length) {
        try {
          const ret = decryptB(s);
          if (ret) {
            try {
              const parsed: RawBlackAppConfig = JSON.parse(ret);
              result.vCamList = processEditText(parsed.vCamList);
              result.remoteApp = processEditText(parsed.remoteApp);
            } catch (error) {
              console.warn("config json parse error!", error);
            }
          }
        } catch (error) {
          console.warn("base64 decode error!", error);
        }
      }
    } else {
      console.warn("参数类型错误!");
    }
  } catch (error) {
    console.warn("parseBlackAppConfig error", error);
  }
  return result;
}

function isString(s: any): s is string {
  return typeof s === "string";
}

/** 换行符分割 */
function processEditText(text: string) {
  return isString(text)
    ? text
        .split(/\r|\n/g)
        .map((s) => s.trim())
        .filter(Boolean)
    : [];
}

function mergeBlackAppConfig(
  remoteConfig: ParsedBlackAppConfig
): MergedBlackAppConfig {
  const result: MergedBlackAppConfig = {
    vCamList: [],
    remoteApp: "",
  };
  try {
    if (
      remoteConfig &&
      typeof remoteConfig === "object" &&
      remoteConfig.vCamList
    ) {
      const { vCamList, remoteApp } = remoteConfig;
      result.vCamList = [...new Set([...vCamList, ...VCAM_LIST])];
      result.remoteApp = [
        ...new Set(REMOTE_APP_NAME.split(";").concat(...remoteApp)),
      ].join(";");
    }
  } catch (error) {
    console.warn("processBlackAppConfig error", error);
  }
  return result;
}
