/*
 Rookeries frontend server - Main entry point to the server.

 @copyright (c) Copyright 2013-2016 Dorian Pula
 @license AGPL v3
 @author Dorian Pula [dorian.pula@amber-penguin-software.ca]
 */

// Polyfill imports
import "babel-polyfill";

// Imports for the application
import express from "express";
import nunjucks from "express-nunjucks";
import proxy from "express-http-proxy";

import { renderReactPage } from "./react_render";
import { formatJson } from "../utils";

// Define some utility functions.
const debug = console.log;

function getRookeriesApiServer() {
    return process.env.ROOKERIES_API_SERVER || 'http://localhost:5000';
}

function getRookeriesApiKey() {
    return process.env.ROOKERIES_API_KEY;
}

function getAppServerPort() {
    return process.env.PORT || 3000;
}

// Create an app.
const app = express();
app.use('/static', express.static("static"));

app.set('view engine', 'html');
app.set('views', 'templates');

nunjucks(app, {autoescape: true, watch: true});

app.get("/", renderReactPage);
app.all("/api/*",
    proxy(
        getRookeriesApiServer(),
        {
            decorateRequest: (proxyRequest) => {
                // Function takes in both the proxy request and original request.
                proxyRequest.headers.ROOKERIES_API_KEY = getRookeriesApiKey();
                return proxyRequest;
            }
        }
    ));
app.post("/auth", proxy(getRookeriesApiServer()));
app.get("/:page", renderReactPage);

// Create a server to run the app.
const server = app.listen(
    getAppServerPort(),
    () => {
        let serverInfo = formatJson(server.address());
        debug(`Web App server started at ${serverInfo}`);
        let apiServer = getRookeriesApiServer();
        debug(`Forwarding API calls to ${apiServer}, using API Key ${getRookeriesApiKey()}.`);
    });
