"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _fsExtra = _interopRequireDefault(require("fs-extra"));

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

var _setup = require("../setup");

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

/* eslint-disable no-param-reassign, require-atomic-updates, fp/no-mutation, fp/no-unused-expression */
const PAGES = _path.default.join(__dirname, "../../static/pages");

async function app(ctx) {
  const themeId = (0, _setup.getTheme)(ctx);
  const localeId = (0, _setup.getLocale)(ctx);

  const filepath = _path.default.join(PAGES, themeId, localeId, ctx.path, "index.html");

  if (_fsExtra.default.existsSync(filepath)) {
    ctx.status = 200;
    ctx.type = "text/html; charset=utf-8";
    ctx.body = _fsExtra.default.createReadStream(filepath);
    return;
  }

  const context = {};
  const html = await (0, _markup.default)({
    url: ctx.url,
    context,
    themeId,
    localeId
  });

  if (!html && context.url) {
    ctx.redirect(context.url);
    return;
  }

  ctx.status = 200;
  ctx.type = "text/html; charset=utf-8";
  ctx.body = `<!DOCTYPE html>${html}`;
}

var _default = app;
exports.default = _default;