import express from "express";
import compression from "compression";

import http from "http";
import path from "path";
import fs from "fs";

class DevServer{
    constructor(config){
        this.config = Object.assign(
            {
                //https: false
            },
            config
        );
    }

    start(){
        const app = express();
        let hostedDir = this.config.outDir||"./";
        let relativeDir = path.relative(path.resolve("."), hostedDir);

        // Configure proxy settings
        app.set('trust proxy', true);

        // GZIP all assets
        app.use(compression());

        app.use(express.static(hostedDir));


        let listenServer = (server)=>((err)=>{
            if (this.config.port === undefined) {
                this.config.port = server.address().port;
            }
            if (this.config.host === undefined) {
                if(server.address().address && server.address().address !== '::'){
                    this.config.host = server.address().address;
                }else{
                    this.config.host = "127.0.0.1";
                }
            }
            console.log(`DevServer started ${relativeDir} -> http://${this.config.host}:${this.config.port } !`);
        });

        let httpServer = http.createServer(app);
        httpServer.listen({
            port:this.config.port,
            host:this.config.host
        }, listenServer(httpServer));
    }
}

let devConfig = {
    outDir: "www",
    port: 41025,// (leave port undefined to have the dev server auto-assign a port again)
};

// Webserver
console.log("Starting webserver...");
let devServer = new DevServer(devConfig);
devServer.start();