import collect from 'bisheng/collect';
import zhCN from '@enos/dpl/lib/locale/lang/zh_CN';
import {Locale} from '@enos/dpl';

import MainContent from './MainContent';
import * as utils from '../utils';

Locale.use(zhCN);

function isChangelog(pathname) {
  return pathname.indexOf('changelog') >= 0;
}

const fixedPathMap = {
  'docs/spec/': 'docs/temp/spec/'
};

function getFixedPath(pathname) {
  const keys = Object.keys(fixedPathMap);
  let fixedPath = pathname;
  for (let i = 0; i < keys.length; i++) {
    if (pathname.startsWith(keys[i])) {
      fixedPath = pathname.replace(keys[i], fixedPathMap[keys[i]]);
      break;
    }
  }
  return fixedPath;
}

export default collect(async(nextProps) => {
  const {pathname} = nextProps.location;
  const fixedPathname = getFixedPath(pathname);
  const pageDataPath = fixedPathname.replace('-cn', '').split('/');
  const pageData = isChangelog(fixedPathname)
    ? nextProps.data.changelog.CHANGELOG
    : nextProps.utils.get(nextProps.data, pageDataPath);
  if (!pageData) {
    throw 404; // eslint-disable-line no-throw-literal
  }

  const locale = utils.isZhCN(fixedPathname) ? 'zh-CN' : 'en-US';
  const pageDataPromise = typeof pageData === 'function'
    ? pageData()
    : (pageData[locale] || pageData.index[locale] || pageData.index)();
  const demosFetcher = nextProps.utils.get(nextProps.data, [...pageDataPath, 'demo']);
  if (demosFetcher) {
    const [localizedPageData, demos] = await Promise.all([pageDataPromise, demosFetcher()]);
    return {localizedPageData, demos};
  }
  return {localizedPageData: await pageDataPromise};
})(MainContent);
