import { getApps } from '@arcblock/ux/lib/Util/federated';
import { isUrl } from '@arcblock/ux/lib/Util';
import { joinURL, withQuery } from 'ufo';
import semver from 'semver';
import bridge from '@arcblock/bridge';
import pathToRegexp from 'path-to-regexp';

import { BLOCKLET_SERVICE_PATH_PREFIX } from '../../constant';
import { logger } from '../../utils';

const BLACK_LIST = [
  `${BLOCKLET_SERVICE_PATH_PREFIX}/connect`,
  `${BLOCKLET_SERVICE_PATH_PREFIX}/login`,
  `${BLOCKLET_SERVICE_PATH_PREFIX}/invite`,
  `${BLOCKLET_SERVICE_PATH_PREFIX}/issue-passport`,
  `${BLOCKLET_SERVICE_PATH_PREFIX}/oauth/*`,
];

const blackListRoute = BLACK_LIST.map((item) => pathToRegexp(item, []));

export async function login() {
  const blocklet = window?.blocklet || {};
  const currentPath = window.location.pathname;
  const { componentId, CHAIN_TYPE: chainType = 'arcblock', appPid } = blocklet;
  const matched = blackListRoute.some((item) => item.exec(currentPath));
  if (matched) {
    return null;
  }

  const apps = getApps();

  try {
    // eth 多个地址和统一登录该如何组合？
    // member 的 url
    const searchParams = new URLSearchParams(window.location.search);
    const inviter = searchParams.get('inviter') || localStorage.getItem('inviter');
    const target = withQuery(joinURL(window.location.origin, BLOCKLET_SERVICE_PATH_PREFIX, '/api/user/loginByWallet'), {
      inviter,
    });
    const data = await bridge.asyncCall('arcLogin', {
      target,
      chainType,
      appPid,
      componentId,
      apps: apps.map((x) => {
        let appLogo = x?.appLogo;
        if (!isUrl(appLogo)) {
          appLogo = joinURL(x.appUrl, appLogo);
        }
        return {
          appName: x.appName,
          appPid: x.appPid,
          appUrl: x.appUrl,
          appLogo,
          sourceAppPid: x.sourceAppPid,
        };
      }),
    });
    return data;
  } catch (err) {
    logger.error('Failed login mobile', err);
    return null;
  }
}

export async function getMobileVisitorId() {
  const result = await bridge.asyncCall('arcGetVisitorId');
  return result;
}

export function checkEnableAutoLogin({ platform, version } = {}) {
  if (platform === 'ios' && version && semver.gte(version, '4.15.6')) {
    return true;
  }
  if (platform === 'android' && version && semver.gte(version, '4.15.1')) {
    return true;
  }

  return false;
}
