"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createServer = void 0;
const express_1 = __importDefault(require("express"));
const body_parser_1 = __importDefault(require("body-parser"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const index_1 = require("../kraken_starter/index");
function createServer(targetDir, port = 3300) {
    const app = express_1.default();
    const buildDir = path_1.default.join(__dirname, '../client_build');
    app.use('/css', express_1.default.static(path_1.default.join(buildDir, 'css')));
    app.use('/js', express_1.default.static(path_1.default.join(buildDir, 'js')));
    app.use('/assets', express_1.default.static(path_1.default.join(buildDir, 'assets')));
    app.use('/', express_1.default.static(buildDir));
    app.use(body_parser_1.default.json());
    let currentDebugCode = '';
    app.get('/preview-suit', (req, res) => {
        const readStream = fs_1.default.createReadStream(path_1.default.join(buildDir, 'index.html'));
        readStream.pipe(res);
    });
    app.get('/', (req, res) => {
        res.redirect('/preview-suit');
    });
    app.get('/webf_debug_server.js', (req, res) => {
        res.setHeader('Content-Type', 'application/javascript');
        return res.end(currentDebugCode);
    });
    app.get('/api/debug_layout', (req, res) => {
        let debug = req.query.debug;
        index_1.triggerDebugLayout(debug == '1' ? true : false).then(() => {
            res.end();
        }).catch(() => {
            res.status(500);
            res.end();
        });
    });
    app.post('/api/start_kraken', (req, res) => {
        let spec = req.body.spec;
        if (!spec.content) {
            return res.json({
                errno: 1,
                errmsg: '获取代码失败'
            });
        }
        return index_1.launchLocalKraken(targetDir, spec).then(() => {
            res.json({
                errno: 0
            });
        }).catch(err => {
            res.json({
                errno: 1,
                errmsg: err.message
            });
        });
    });
    app.post('/api/polyfill_content', (req, res) => {
        let spec = req.body.spec;
        let code = index_1.patchPolyfill(targetDir, spec);
        return res.json({
            code: code
        });
    });
    app.post('/api/set_debug_server', (req, res) => {
        let code = req.body.code;
        currentDebugCode = code;
        return res.end();
    });
    const server = app.listen(port);
    return server;
}
exports.createServer = createServer;
