import express = require('express');
import bodyParser = require('body-parser');
import routers = require('../routers/router');
import compression = require('compression');
import * as fallback from 'express-history-api-fallback';
import * as path from "path";
import { watch } from '../middleware/watch';
import { httpErrorHandler } from '../middleware/httpErrorHandler';
import { DataExtractor } from "../util/dataExtractor";

export class httpServer {
   static createServer(port: number, host: string) {
       const httpServer = express();
    
       httpServer.all('*', (req, res, next) => {
           res.header('Access-Control-Allow-Origin', req.headers.origin);
           res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization");
           res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
           res.header('Access-Control-Allow-Credentials', 'true');
           res.header("X-Powered-By", '3.2.1');
           if (req.method === 'OPTIONS') {
               res.sendStatus(200);
           } else {
               next();
           }
       });

       httpServer.use(bodyParser.json({ limit: "10kb" }));
       httpServer.use(compression());
    
       httpServer.use(watch);
       routers.setRouter(httpServer);
       httpServer.use(httpErrorHandler);
    
       httpServer.use(express.static(path.join(__dirname, "../../img/")));
       httpServer.use(express.static(path.join(__dirname, "../../pdf/")));

       const root = path.join(__dirname, "../../public/");
       httpServer.use(express.static(root));
       httpServer.use(fallback('index.html', { root }));

       console.log(`Server is listening at http://${host}:${port}`);
       httpServer.listen(port, host, () => {
           console.log(`Server started at http://${host}:${port}`);
       });

       DataExtractor.getInstance();

       return httpServer;
   }
}
