import "core-js/modules/es.regexp.exec.js";
import { pathToRegexp } from 'path-to-regexp';
import { isUrl } from '../utils';
function findPathKeyByPathname(pathname, breadcrumb) {
  if (breadcrumb) {
    const pathKey = Object.keys(breadcrumb).find(key => {
      if (isUrl(key)) {
        return '';
      }
      return pathToRegexp(key).test(pathname);
    });
    return pathKey;
  }
  return '';
}
export const matchParamsPath = (pathname, breadcrumb, breadcrumbMap) => {
  // Internal logic use breadcrumbMap to ensure the order
  // 内部逻辑使用 breadcrumbMap 来确保查询顺序
  if (breadcrumbMap) {
    const pathKey = findPathKeyByPathname(pathname, breadcrumbMap);
    if (pathKey) {
      return breadcrumbMap.get(pathKey);
    }
  }

  // External uses use breadcrumb
  // 外部用户使用 breadcrumb 参数
  if (breadcrumb) {
    const pathKey = findPathKeyByPathname(pathname, breadcrumb);
    if (pathKey) {
      return breadcrumb[pathKey];
    }
  }
  return {
    path: ''
  };
};
/**
 * 获取关于 pageTitle 的所有信息方便包装
 *
 * @param props
 * @param ignoreTitle
 */
const getPageTitleInfo = (props, ignoreTitle) => {
  const {
    pathname = '/',
    breadcrumb,
    breadcrumbMap,
    formatMessage,
    title = 'Wau',
    menu = {
      locale: false
    }
  } = props;
  const pageTitle = ignoreTitle ? '' : title || '';
  const currRouterData = matchParamsPath(pathname, breadcrumb, breadcrumbMap);
  if (!currRouterData) {
    return {
      title: pageTitle,
      id: '',
      pageName: pageTitle
    };
  }
  let pageName = currRouterData.name;
  if (menu.locale !== false && currRouterData.locale && formatMessage) {
    pageName = formatMessage({
      id: currRouterData.locale || '',
      defaultMessage: currRouterData.name
    });
  }
  if (!pageName) {
    return {
      title: pageTitle,
      id: currRouterData.locale || '',
      pageName: pageTitle
    };
  }
  if (ignoreTitle || !title) {
    return {
      title: pageName,
      id: currRouterData.locale || '',
      pageName
    };
  }
  return {
    title: `${pageName} - ${title}`,
    id: currRouterData.locale || '',
    pageName
  };
};
export { getPageTitleInfo };
const getPageTitle = (props, ignoreTitle) => {
  return getPageTitleInfo(props, ignoreTitle).title;
};
export default getPageTitle;