"use strict";

const express = require("express"),
  fs = require("fs"),
  url = require("url"),
  config = require("config"),
  basePath = require("../basepath");

const router = express.Router();

/* List of filename extensions we know are "potential" file extensions for
* assets we don"t want to return "index.html" for */
const extensions = [
  "html", "js", "css", "eot", "gif", "ico", "jpeg", "jpg", "mp4",
  "md", "ttf", "txt", "woff", "woff2", "yml", "svg"
];

/* Build the extension match RegExp from the list of extensions */
const extensionMatch = new RegExp("^.*?(" + extensions.join("|") + ")$", "i");

/* To handle dynamic routes, we return index.html to every request that
 * gets this far -- so this needs to be the last route.
 *
 * However, that introduces site development problems when assets are
 * referenced which don't yet exist (due to bugs, or sequence of adds) --
 * the server would return HTML content instead of the 404.
 *
 * So, check to see if the requested path is for an asset with a recognized
 * file extension.
 *
 * If so, 404 because the asset isn't there. otherwise assume it is a
 * dynamic client side route and *then* return index.html.
 */
router.get("/*", function(req, res, next) {
  const parts = url.parse(req.url);

  /* If req.user isn't set yet (authentication hasn't happened) then
   * only allow / to be loaded--everything else chains to the next 
   * handler */
  if (!req.user && 
      req.url != "/" && 
      req.url.indexOf("/games") != 0) {
    return next();
  }
  
  if (req.url == "/" || req.url.indexOf("/games") == 0 || !extensionMatch.exec(parts.pathname)) {
    console.log("Returning index for " + req.url);

    /* Replace <script>'<base href="BASEPATH">';</script> in index.html with
     * the basePath */
    const frontendPath = config.get("frontendPath").replace(/\/$/, "") + "/",
      index = fs.readFileSync(frontendPath + "index.html", "utf8");
    res.send(index.replace(
      /<script>'<base href="BASEPATH">';<\/script>/,
      "<base href='" + basePath + "'>"));
    return;
  }

  console.log("Page not found: " + req.url);
  return res.status(404).json({
    message: "Page not found",
    status: 404
  });
});

module.exports = router;
