"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.closeServer = exports.openServer = void 0;
const express_1 = __importDefault(require("express"));
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const cors_1 = __importDefault(require("cors"));
const debug_1 = __importDefault(require("debug"));
const loggerDebug = debug_1.default('screenplay:debug');
const loggerError = debug_1.default('screenplay:error');
let server;
function openServer(port, testPath) {
    const app = express_1.default();
    loggerDebug('testPath', testPath);
    app.use(noCacheMiddleware);
    app.use(cors_1.default({ origin: ['http://localhost:3000'] }));
    app.use(express_1.default.static(path_1.default.resolve(__dirname, '../dist/static')));
    app.use(express_1.default.static(path_1.default.resolve(__dirname, '../static')));
    app.use('/results', express_1.default.static(testPath));
    app.get('/test/:testname', async (req, res) => {
        try {
            const results = JSON.parse((await fs_extra_1.default.readFile(path_1.default.resolve(testPath, 'results.json'), 'utf-8')));
            res.json(results);
        }
        catch (e) {
            res.status(500).end('Error loading result');
        }
    });
    app.get('/new-steps/:laststep', (req, res) => res.send('OK'));
    return new Promise((resolve, reject) => {
        server = app.listen(port, err => {
            if (err) {
                loggerError(err);
                console.error(err);
                reject(err);
            }
            const url = `http://localhost:${port}`;
            loggerDebug(`screenplay available at: ${url}`);
            resolve(url);
        });
    });
}
exports.openServer = openServer;
function closeServer() {
    server.close();
}
exports.closeServer = closeServer;
function noCacheMiddleware(_request, response, next) {
    response.setHeader('Surrogate-Control', 'no-store');
    response.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
    response.setHeader('Pragma', 'no-cache');
    response.setHeader('Expires', '0');
    next();
}
