"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var fsx = _interopRequireWildcard(require("fs-extra"));

var _path = _interopRequireDefault(require("path"));

var _markup = _interopRequireDefault(require("./markup"));

var _config = require("./config");

var _data = require("./data");

/* eslint-disable fp/no-unused-expression, @typescript-eslint/ban-ts-ignore */
const OUT = _path.default.join(__dirname, "../static/pages");

const themeIds = Object.keys(_data.themes);
const intlIds = Object.keys(_data.locales);

const makeStream = async (themeId, localeId, url) => {
  const fileDir = _path.default.join(OUT, themeId, localeId, url);

  fsx.ensureDirSync(fileDir);
  const context = {};
  const html = await (0, _markup.default)({
    url,
    context,
    themeId,
    localeId
  });

  if (!html) {
    return Promise.reject(new Error(`Invalid pre-render URL: ${context.url}`));
  }

  return fsx.writeFile(_path.default.join(fileDir, "index.html"), `<!DOCTYPE html>${html}`);
};

const makeRoutes = (themeId, intlId) => // @ts-ignore - dunno what is its problem
_config.routes.reduce((routeAcc, route) => routeAcc.concat(makeStream(themeId, intlId, route)), []);

const makeIntls = themeId => // @ts-ignore - dunno what is its problem
intlIds.reduce((intlAcc, intlId) => intlAcc.concat(makeRoutes(themeId, intlId)), []);

function render() {
  const oks = Promise.all( // @ts-ignore - dunno what is its problem
  themeIds.reduce((themeAcc, themeId) => themeAcc.concat(makeIntls(themeId)), []));
  return oks.catch(err => {
    console.error("[render] Error!", err); // eslint-disable-line no-console
  });
}

render();