import bodyParser from "body-parser";
import express from "express";
import http from "http";
import sourceMapSupport from "source-map-support";
import SessionService from "../application/PrintService";
import routeRest from "./routeREST";

export default class RESTServer {

    public port: number;
    public sessionService: SessionService;

    constructor(port, sessionService) {
        this.port = port;
        this.sessionService = sessionService;
    }

    public start(): void {
        // Create server
        const app: express = express();
        const port: number = parseInt(process.env.PORT, 10) || this.port;
        const server: http.Server = http.createServer(app);

        // logger
        if (process.env.NODE_ENV === "development") {
            // tslint:disable-next-line: typedef
            const morgan = require("morgan");
            sourceMapSupport.install();
            app.use(morgan("combined"));
        }

        // attach routes
        app.use((req, res, next) => {
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
            res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type");
            res.setHeader("Access-Control-Allow-Credentials", true);
            next();
        });

        // request parser
        app.use(bodyParser.json({limit: "10mb", extended: true}));
        app.use(bodyParser.urlencoded({limit: "10mb", extended: true}));

        // WebSite route
        routeRest(app, this.sessionService);

        // Start server
        server.listen(port, () => {
            console.log("server is listening on port", this.port);
        });

    }

}
