"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const ramda_1 = require("ramda");
const screenUtils_1 = require("../../utils/screenUtils");
const path_1 = require("path");
const express = require('express');
let basePort = 15000;
const unusedPorts = [];
class StaticServer {
    static create(staticDir, settings) {
        return new StaticServer(staticDir, settings);
    }
    constructor(staticDir, settings) {
        this._staticDir = staticDir;
        this._expressServer = express();
        this._settings = settings;
        this._listener = null;
        this.port = basePort;
    }
    initialize() {
        const server = this._expressServer;
        server.get('/settings.json', (req, res, next) => __awaiter(this, void 0, void 0, function* () {
            const { query } = req;
            if ((0, ramda_1.isEmpty)(query)) {
                next();
                return;
            }
            const editingSettings = (0, ramda_1.mergeDeepRight)(this._settings, (0, screenUtils_1.convertScreenCommandsToSettingsView)(this._settings, query));
            res.json(editingSettings);
        }));
        server.get('*', express.static(this._staticDir, { dotfiles: 'allow' }));
        server.get('*', (req, res) => __awaiter(this, void 0, void 0, function* () {
            res.sendFile((0, path_1.join)(this._staticDir, 'index.html'));
        }));
        this.port = getFreePort();
        return new Promise((resolve) => {
            this._listener = server.listen(this.port, () => resolve(this.port));
        });
    }
    destroy() {
        if (!this._listener) {
            console.log('No listener');
        }
        else {
            this._listener.close();
        }
        freePort(this.port);
    }
}
exports.default = StaticServer;
function getFreePort() {
    if (unusedPorts.length === 0) {
        basePort += 1;
        return basePort;
    }
    return unusedPorts.pop();
}
function freePort(port) {
    unusedPorts.push(port);
}
//# sourceMappingURL=index.js.map