"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 child_process_1 = __importDefault(require("child_process"));
const loggerDebug = debug_1.default('root-cause:debug');
const loggerError = debug_1.default('root-cause:error');
const DEV_STATIC_FILES_LOCATION = path_1.default.resolve(__dirname, '../../client/build');
const PROD_STATIC_FILES_LOCATION = path_1.default.resolve(__dirname, '../client-static');
const STATIC_INDEX_FILE = 'index.html';
let server;
async function buildClientStatics() {
    await new Promise((res, rej) => {
        child_process_1.default.exec('yarn workspace @testim/root-cause-client-bundled build -s', {
            windowsHide: true,
        }, (error, sdtOut, stdErr) => {
            if (error) {
                rej(sdtOut);
            }
            else {
                res();
            }
        });
    });
    if (!(await fs_extra_1.default.pathExists(path_1.default.resolve(DEV_STATIC_FILES_LOCATION, STATIC_INDEX_FILE)))) {
        throw new Error('Dev statics are missing after build, this is not expected.');
    }
}
function isDevMode() {
    return __filename.endsWith('.ts');
}
async function openServer(port, testPath) {
    const app = express_1.default();
    loggerDebug('testPath', testPath);
    if (isDevMode()) {
        console.log('--- Dev mode detected ---');
        console.log('For better client development experience, you may start the client dev server on a new terminal using:');
        console.log('yarn workspace @testim/root-cause-client-bundled start');
        console.log('but keep this server also running');
        if (!(await fs_extra_1.default.pathExists(path_1.default.resolve(DEV_STATIC_FILES_LOCATION, STATIC_INDEX_FILE)))) {
            console.log('Client Static files not found, building client project...');
            try {
                await buildClientStatics();
                console.log('Done building client project');
            }
            catch (e) {
                console.warn(e);
                console.warn('Building client project failed. you can keep this running, and use the CRA dev server');
                console.warn("If you keep seeing this message and the CRA start don't have any errors, please open an issue");
            }
        }
    }
    else if (!(await fs_extra_1.default.pathExists(path_1.default.resolve(PROD_STATIC_FILES_LOCATION, STATIC_INDEX_FILE)))) {
        console.error("Missing client static, there's an issue with the package integrity");
        console.error('Please report an issue');
        throw new Error("Missing client static, there's an issue with the package integrity");
    }
    if (!(await fs_extra_1.default.pathExists(path_1.default.resolve(testPath, 'results.json')))) {
        console.error({ testPath });
        throw new Error('testPath dose not exist');
    }
    app.use(cors_1.default({ origin: ['http://localhost:3000'] }));
    app.use(noCacheMiddleware);
    app.use(express_1.default.static(PROD_STATIC_FILES_LOCATION));
    app.use(express_1.default.static(DEV_STATIC_FILES_LOCATION));
    app.use('/results', express_1.default.static(testPath));
    app.get('/test/', 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) {
            console.error({ testPath });
            console.error({ e });
            res.status(500).end('Error loading result');
        }
    });
    app.get('/new-steps/:laststep', (req, res) => res.send('OK'));
    return new Promise((resolve) => {
        server = app.listen(port, () => {
            const url = `http://localhost:${port}`;
            loggerDebug(`root cause 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();
}
