"use strict";

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

var _logger = require("../../logger");

/* eslint-disable no-use-before-define */
function initialHTMLHandling(compiler, app, options) {
  const {
    contextURL,
    enableMockReplace
  } = options;
  const {
    i18nChunkSplit
  } = options;
  const {
    rtlSplit
  } = options.css.plugins;
  const {
    httpsUrl,
    httpUrl
  } = options.serverExtras;
  let initialHTML;
  compiler.hooks.afterCompile.tap('ReactCLI', compilation => {
    const indexHtml = compilation.assets['index.html']; // compiler.outputFileSystem.readFileSync("build/index.html");

    if (indexHtml) {
      initialHTML = indexHtml.source();
    }
  });
  compiler.hooks.compile.tap('ReactCLI', () => {
    (0, _logger.messageLogger)('Webpack re-building .......');
  });
  app.use(`${contextURL}/*`, (req, res) => {
    const newHTML = modifyInitialHTML({
      initialHTML,
      options,
      enableMockReplace,
      req
    });
    res.send(newHTML);
  });

  function modifyInitialHTML({
    initialHTML,
    enableMockReplace,
    req
  }) {
    let newHTML = enableMockReplace && initialHTML ? mockReplace(initialHTML, req.query) : initialHTML;

    if (req.protocol === 'http') {
      newHTML = newHTML.replaceAll(httpsUrl, httpUrl);
    }

    return newHTML;
  }

  function mockReplace(inputHTML, query) {
    const {
      dir,
      locale
    } = query || {};
    let newHTML = inputHTML;

    if (i18nChunkSplit.chunkSplitEnable) {
      newHTML = replaceWithRandomLocale(newHTML, i18nChunkSplit.templateLabel, locale);
    }

    if (rtlSplit.enableRTLSplit) {
      newHTML = replaceWithRandomDir(newHTML, rtlSplit.templateLabel, dir);
    }

    return newHTML;
  }

  function replaceWithRandomLocale(initialHTML, templateLabel, queryLocale) {
    const locales = ['ar_EG', 'da_DK', 'de_DE', 'en_US', 'es_AR', 'es_ES', 'fr_FR', 'hi_IN', 'in_ID', 'it_IT', 'iw_IL', 'ja_JP', 'nl_NL', 'pl_PL', 'pt_BR', 'pt_PT', 'ro_RO', 'ru_RU', 'sv_SE', 'ta_IN', 'te_IN', 'tr_TR', 'zh_CN', 'zh_TW']; // app.use(`/desk/*`, (req, res) => {
    // const locale = 'ta_IN';

    const locale = queryLocale || locales[Math.floor(Math.random() * locales.length)];
    (0, _logger.verboseLogger)({
      locale
    });
    return initialHTML.replaceAll(templateLabel, locale);
  }

  function replaceWithRandomDir(initialHTML, templateLabel, queryDir) {
    const dirs = ['ltr', 'rtl']; // const dir = 'rtl';

    const dir = queryDir || dirs[Math.floor(Math.random() * dirs.length)];
    (0, _logger.verboseLogger)({
      dir
    });
    return initialHTML.replaceAll(templateLabel, dir);
  }
}