import FingerprintJS from "@fingerprintjs/fingerprintjs";

//用于生成的配置信息
/* const components = [
  { key: "userAgent", getData: UserAgent }, //用户代理
  { key: "webdriver", getData: webdriver }, //网页内驱动软件
  { key: "language", getData: languageKey }, //语言种类
  { key: "colorDepth", getData: colorDepthKey }, //目标设备或缓冲器上的调色板的比特深度
  { key: "deviceMemory", getData: deviceMemoryKey }, //设备内存
  { key: "pixelRatio", getData: pixelRatioKey }, //设备像素比
  { key: "hardwareConcurrency", getData: hardwareConcurrencyKey }, //可用于运行在用户的计算机上的线程的逻辑处理器的数量。
  { key: "screenResolution", getData: screenResolutionKey }, //当前屏幕分辨率
  { key: "availableScreenResolution", getData: availableScreenResolutionKey }, //屏幕宽高（空白空间）
  { key: "timezoneOffset", getData: timezoneOffset }, //本地时间与 GMT 时间之间的时间差，以分钟为单位
  { key: "timezone", getData: timezone }, //时区
  { key: "sessionStorage", getData: sessionStorageKey }, //是否会话存储
  { key: "localStorage", getData: localStorageKey }, //是否具备本地存储
  { key: "indexedDb", getData: indexedDbKey }, //是否具备索引DB
  { key: "addBehavior", getData: addBehaviorKey }, //IE是否指定AddBehavior
  { key: "openDatabase", getData: openDatabaseKey }, //是否有打开的DB
  { key: "cpuClass", getData: cpuClassKey }, //浏览器系统的CPU等级
  { key: "platform", getData: platformKey }, //运行浏览器的操做系统和(或)硬件平台
  { key: "doNotTrack", getData: doNotTrackKey }, //do-not-track设置
  { key: "plugins", getData: pluginsComponent }, //浏览器的插件信息
  { key: "canvas", getData: canvasKey }, //使用 Canvas 绘图
  { key: "webgl", getData: webglKey }, //WebGL指纹信息
  { key: "webglVendorAndRenderer", getData: webglVendorAndRendererKey }, //具备大量熵的WebGL指纹的子集
  { key: "adBlock", getData: adBlockKey }, //是否安装AdBlock
  { key: "hasLiedLanguages", getData: hasLiedLanguagesKey }, //用户是否篡改了语言
  { key: "hasLiedResolution", getData: hasLiedResolutionKey }, //用户是否篡改了屏幕分辨率
  { key: "hasLiedOs", getData: hasLiedOsKey }, //用户是否篡改了操做系统
  { key: "hasLiedBrowser", getData: hasLiedBrowserKey }, //用户是否篡改了浏览器
  { key: "touchSupport", getData: touchSupportKey }, //触摸屏检测和能力
  { key: "fonts", getData: jsFontsKey, pauseBefore: true }, //使用JS/CSS检测到的字体列表
  { key: "fontsFlash", getData: flashFontsKey, pauseBefore: true }, //已安装的Flash字体列表
  { key: "audio", getData: audioKey }, //音频处理
  { key: "enumerateDevices", getData: enumerateDevicesKey } //可用的多媒体输入和输出设备的信息。
]; */

//闭包存储FingerPrint 降低性能开销
const getFingerPrint = () => {
  let fingerPrintKey;
  return () => {
    if (fingerPrintKey) {
      return Promise.resolve(fingerPrintKey);
    } else {
      return new Promise((resolve, reject) => {
        //保证指纹一致性，创建宏任务线程操作时间保证 配置项获取值一致
        if (window.requestIdleCallback) {
          requestIdleCallback(async () => {
            fingerPrintKey = await createFingerPrint();
            resolve(fingerPrintKey);
          });
        } else {
          setTimeout(async () => {
            fingerPrintKey = await createFingerPrint();
            resolve(fingerPrintKey);
          }, 500);
        }
      });
    }
  };
};

//调用指纹库生成指纹
const createFingerPrint = async () => {
  //配置默认项 v2有 V3无配置项
  /* const defaultOptions = {
    preprocessor: null,
    audio: {
      timeout: 1000,
      // 在iOS 11上，音频上下文只能用于响应用户交互。我们要求用户在iOS 11上显式启用音频指纹https://stackoverflow.com/questions/46363048/onaudioprocess-not-called-on-ios11#46534088
      excludeIOS11: true
    },
    screen: {
      // 当用户旋转移动设备时确保指纹一致
      detectScreenOrientation: true
    },
    //包含项稳定的参数来源https://github.com/Valve/fingerprintjs2/wiki/Stable-components
    excludes: {
      language: true,
      colorDepth: true,
      deviceMemory: true,
      pixelRatio: true,
      availableScreenResolution: true,
      timezoneOffset: true,
      timezone: true,
      sessionStorage: true,
      localStorage: true,
      indexedDb: true,
      addBehavior: true,
      openDatabase: true,
      cpuClass: true,
      doNotTrack: true,
      plugins: true,
      canvas: true,
      webglVendorAndRenderer: true, 
      adBlock: true,
      hasLiedLanguages: true,
      hasLiedResolution: true,
      hasLiedOs: true,
      hasLiedBrowser: true,
      touchSupport: true,
      audio: false,
      enumerateDevices: true,
      hardwareConcurrency: true
    }
  }; */

  //免费版无密钥初始化
  const fpPromise = FingerprintJS.load();
  //获取回调对象
  const fp = await fpPromise;
  //获取指纹密钥
  try {
    const { visitorId } = await fp.get();
    return visitorId;
  } catch (error) {
    switch (error.message) {
      case FingerprintJS.ERROR_GENERAL_SERVER_FAILURE:
        console.log("Unknown server error. Request id:", error.requestId);
        break;
      case FingerprintJS.ERROR_CLIENT_TIMEOUT:
        console.log("Identification time limit of 10 seconds is exceeded");
        break;
      default:
        console.log("Other error");
    }
  }
};

const getFingerPrintFunc = getFingerPrint();

export default getFingerPrintFunc;
