import express = require('express');
import bodyParser = require('body-parser');
import sign = require('../middleware/sign');
import routers = require('../routers/router');
import compression = require('compression');
import * as fallback from 'express-history-api-fallback';
import * as path from "path";


export class httpServer {
   static createServer(port:number) {
    var httpServer = express();
    
    httpServer.all('*',function (req, res, next) {
      res.header('Access-Control-Allow-Origin', req.headers.origin);
      res.header("Access-Control-Allow-Headers", "X-Requested-With");
      res.header('Access-Control-Allow-Headers', 'Content-Type');
      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.statusCode = 200;
          res.end();
        }else{
            next();
        }
    });

    httpServer.use(express.static('public') );
    httpServer.use(express.static('img') );

    httpServer.use(bodyParser.json({limit:"10kb"}));
    httpServer.use(compression())
    routers.setRouter(httpServer);

    const root = path.join(__dirname, "../../public/")
    httpServer.use(express.static(root))
    httpServer.use(fallback('index.html', { root }))
    console.log('web listen on port:'+port);
    
    
    httpServer.listen(port);
    console.log('server listen on port:'+port);
    
    return httpServer;
  }
}
