var express = require("express")
var morgan = require("morgan")
var { createProxyMiddleware } = require("http-proxy-middleware")
var historyFallback = require("connect-history-api-fallback")
var app = express()
app.use(morgan("dev"))

var port = process.env.PORT || 3000
var host = process.env.HOST || "0.0.0.0"
var api = process.env.API
var index = process.env.INDEX
var ssr = process.env.SSR

var apiFrom = ""
var apiTo = ""

if (api) {
    var _api = api.split(":")
    apiFrom = _api[0]
    for (var i = 1; i < _api.length; i++) {
        if (apiTo) apiTo = apiTo + ":"
        apiTo = apiTo + _api[i]
    }

    if (apiFrom && apiTo) {
        console.log("using api: " + apiFrom + " -> " + apiTo)
        var _pR = {}
        _pR["^" + apiFrom] = ""
        app.use(
            apiFrom,
            createProxyMiddleware({
                target: apiTo,
                changeOrigin: true,
                pathRewrite: _pR,
            })
        )
    }
}

app.use(express.static(process.env.WEBROOT || "/data"))

if (ssr) {
    console.log("using ssr via: " + ssr)
    app.use(
        createProxyMiddleware({
            target: ssr,
            changeOrigin: true,
        })
    )
}

if (index) {
    console.log("using default index: " + index)
    app.use(historyFallback({ index: index, verbose: true, disableDotRule: true }))
    app.get(index, function (req, res) {
        res.sendFile(index, {
            root: process.env.WEBROOT || "/data",
        })
    })
}

app.use(function (req, res, next) {
    res.status(404).end()
})

var server = app.listen(port, host)
