import express = require('express');
import bodyParser = require('body-parser');
import routers = require('../routers/router');
import compression = require('compression');
import { watch } from '../middleware/watch';
import { httpErrorHandler } from '../middleware/httpErrorHandler';
import * as path from "path";
import fallback from 'express-history-api-fallback';
import historyFallback from 'express-history-api-fallback'; // 正确导入默认导出的函数

export class httpServer {
    static createServer(port: number) {
        var 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");
            res.header('Access-Control-Allow-Headers', 'Content-Type,request-origin,userid,token,username');
            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');
            next();
        });



        httpServer.use(express.static('public'));
        httpServer.use(express.static('img'));
        httpServer.use(compression());
        httpServer.use(watch);
        httpServer.use(bodyParser.json({ limit: "500kb" }));
        routers.setRouter(httpServer);
        httpServer.use(httpErrorHandler);
        const root = path.join(__dirname, "../../public");
        httpServer.use(express.static(root))
        // 使用 fallback 函数
        httpServer.use(fallback('index.html', { root }));
        httpServer.use(historyFallback('index.html', { root }));
        console.log('web listen on port:' + port);
        httpServer.listen(port);
        console.log('server listen on port:' + port);
        return httpServer;
    }
}