import { parse } from 'querystring';
import { useLocation, isBrowser } from 'umi';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg =
  /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// For the official demo site, it is used to turn off features that are not needed in the real development environment
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => {
  return parse(window.location.href.split('?')[1]);
  // const location = useLocation();
  // return parse(location.search.slice(1));
};

// 服务端获取查询参数的方法，ssr的时候调用此方法
export const getServerSidePageQuery = ({ ctx }) => {
  if (ctx && ctx.query) {
    return ctx.query;
  }
  return {};
};

export const urlEncode = (str: string) => {
  str = (str + '').toString();
  return encodeURIComponent(str)
    .replace(/!/g, '%21')
    .replace(/'/g, '%27')
    .replace(/\(/g, '%28')
    .replace(/\)/g, '%29')
    .replace(/\*/g, '%2A')
    .replace(/%20/g, '+');
};

export const getAPIHost = () => {
  const env = process.env.NODE_ENV || 'development';
  let host;
  switch (env) {
    case 'prod':
      host = 'https://hi-po.com.cn';
      break;
    case 'production':
      host = 'https://hi-po.com.cn';
      break;
    default:
      host = 'https://hi-po.com.cn';
  }
  return host;
};
