"use strict";
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
var tsServer_1 = require("./tsServer");
var spawn_1 = require("./tsServer/spawn");
var logger_1 = require("./logger");
var LangServersMap = /** @class */ (function () {
    function LangServersMap() {
        this.serversMap = new Map();
    }
    LangServersMap.prototype.createServer = function (payload) {
        var _this = this;
        var existingServer = this.fetchServer(payload);
        if (!!existingServer) {
            // We already have a server
            return existingServer;
        }
        var process = spawn_1.spawnServer();
        process.on("exit", function (code) { return _this.handleExit(payload, code); });
        process.on("error", function (error) { return _this.handleError(payload, error); });
        var tsServer = new tsServer_1.TypeScriptServer(process);
        this.serversMap.set(this.getKey(payload), tsServer);
        return tsServer;
    };
    LangServersMap.prototype.fetchServer = function (payload) {
        return this.serversMap.get(this.getKey(payload));
    };
    LangServersMap.prototype.killServer = function (payload) {
        var server = this.fetchServer(payload);
        if (!!server) {
            server.kill();
            this.serversMap.delete(this.getKey(payload));
        }
    };
    LangServersMap.prototype.info = function () {
        return __spread(this.serversMap.keys());
    };
    LangServersMap.prototype.getKey = function (payload) {
        var name = payload.name, user = payload.user, sha = payload.sha, service = payload.service;
        return service + ":" + user + ":" + name + ":" + sha;
    };
    LangServersMap.prototype.handleExit = function (repo, code) {
        logger_1.log("Server exit: " + code);
        this.serversMap.delete(this.getKey(repo));
    };
    LangServersMap.prototype.handleError = function (repo, error) {
        logger_1.log("Server error: " + error);
    };
    return LangServersMap;
}());
exports.LangServersMap = LangServersMap;
