import compression from 'compression';
import history from 'connect-history-api-fallback';
import express from 'express';
import fs from 'fs';
import https from 'https';
import morgan from 'morgan';
import path from 'path';
import serveStatic from 'serve-static';

const app = express();

const publicDir = 'assets';
// const defaultPage = 'index.html';

const port = 8443;
const ss: any = serveStatic.mime;
function setCustomCacheControl(res, path) {
    if (ss.lookup(path) === 'text/html') {
      // index.html will cached 10 mins
        res.setHeader('Cache-Control', 'public, max-age=600');
    }
}

app
    .use(morgan('combined')) // logger
    .use(compression()) // gzip
    .use('/live', (req, res) => {
        // OpenShift livenessProbe
        res.send('<h1>Application is alive :)</h1>');
    })
    .use(
        history({
            rewrites: [
                {
                    from: /^\/solution-engine\/(.*)/i,
                    to: (context) => {
                        return '/' + context.match[1];
                    }
                }
            ]
        })
    )
    .use(
        serveStatic(path.join(__dirname, publicDir), {
            maxAge: '10d', // all static files except html will be cached 10 days
            setHeaders: setCustomCacheControl
        })
    );

try {
    const cert = fs.readFileSync('/etc/ssl/server.crt');
    const key = fs.readFileSync('/etc/ssl/server.key');

    const options = {
        cert,
        key
    };

    https.createServer(options, app).listen(port, () => {
        console.log('Application started with https');
    });
} catch (err) {
    console.error(err);
    app.listen(port, () => {
        console.log('Application started with http');
    });
}
