"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 generateSuitFile_1 = require("../gen-suits/generateSuitFile");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const uuid_1 = __importDefault(require("uuid"));
const lru_cache_1 = __importDefault(require("lru-cache"));
const file_1 = require("../gen-suits/file");
const index_1 = require("../kraken_starter/index");
const previewCache = new lru_cache_1.default();
function createServer(suits, sourceDir, targetDir, port = 3300) {
    const app = express_1.default();
    const buildDir = path_1.default.join(__dirname, '../client_build');
    app.use('/wpt', express_1.default.static(sourceDir));
    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('/gen-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('/');
    });
    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/update_html', (req, res) => {
        let filePath = req.body.filepath;
        let content = req.body.content;
        let suitIndex = req.body.suitIndex;
        let specIndex = req.body.specIndex;
        suits[suitIndex].specs[specIndex].originalContent = content;
        fs_1.default.writeFile(filePath, content, function (err) {
            if (err) {
                res.status(500);
                return res.end();
            }
            res.status(200);
            res.end();
        });
    });
    app.get('/api/preview_url', (req, res) => {
        let id = req.query.id;
        if (!id) {
            console.error('no preview id');
            res.status(500);
            return res.end();
        }
        let content = previewCache.get(id);
        return res.end(content);
    });
    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/preview_url', (req, res) => {
        const existId = req.query.uuid;
        const content = req.body.content;
        let id;
        if (typeof existId === 'string') {
            previewCache.set(existId, content);
            id = existId;
        }
        else {
            id = uuid_1.default.v4();
            previewCache.set(id, content);
        }
        return res.json({
            status: 'ok',
            url: '/api/preview_url?id=' + id
        });
    });
    app.post('/api/upload', (req, res) => {
        let spec = req.body.spec;
        let code = req.body.code;
        spec.sourceFile = new file_1.SourceFile(spec.sourceFile._originalName, spec.sourceFile._fullPath);
        let msg = generateSuitFile_1.generateSuitFile(targetDir, spec, code);
        res.json({
            success: 0,
            msg: msg
        });
    });
    app.get('/api/suit', (req, res) => {
        let specs = [];
        suits.forEach((suit, index) => {
            suit.specs.forEach((spec, sIndex) => {
                spec.suitName = suit.name;
                spec.suitIndex = index;
                spec.specIndex = sIndex;
                specs.push(spec);
            });
        });
        return res.json(specs);
    });
    app.post('/api/skip', (req, res) => {
        let spec = req.body.spec;
        let status = generateSuitFile_1.skipSuit(targetDir, spec);
        res.json({ status: 'ok' });
    });
    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.get('/webf_debug_server.js', (req, res) => {
        res.setHeader('Content-Type', 'application/javascript');
        return res.end(currentDebugCode);
    });
    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;
