"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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CameraProcessStateColors = exports.CameraPCStateColors = exports.CameraRunner = void 0;
var socket_io_client_1 = require("socket.io-client");
var Utils_1 = require("./Utils");
var Status_1 = require("./Status");
var PREFIX = "[CameraRunner]";
var CameraRunner = /** @class */ (function () {
    function CameraRunner(Main) {
        this.errorTriggerStartupDelay = 10000;
        this.bootTime = Date.now();
        this.state = 'DISCONNECTED';
        this.processStatus = {
            state: 'STOPPED',
            startTime: -1,
            output: { current: [], last: [] },
        };
        this._Main = Main;
    }
    CameraRunner.prototype.handle = function (command) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        switch (command) {
            case 'restart':
            case 'reboot':
                var callback = args[0];
                if (typeof callback !== 'function')
                    return;
                this.sendCommand(command, callback);
                break;
        }
    };
    CameraRunner.prototype.sendCommand = function (command, callback) {
        if (this.socket == null || !this.socket.connected)
            return callback({
                succeed: false,
                message: 'Not connected to CameraRunner',
            });
        this.socket.emit(command, function (response) {
            callback(response);
        });
    };
    CameraRunner.prototype.broadcastState = function () {
        this._Main.WebServer.socket.emit('cameraRunnerState', this.getState());
    };
    CameraRunner.prototype.getState = function () {
        return {
            state: this.state,
            message: this.message,
            error: this.error,
            processStatus: this.processStatus,
        };
    };
    CameraRunner.prototype.setInfo = function (message, error, state) {
        if (state === void 0) { state = 'FAILED'; }
        this.message = message;
        this.error = error;
        this.state = state;
        this._Main.Status.update(Status_1.StatusType.CameraPC, exports.CameraPCStateColors[this.state], message, {
            reboot: state === 'FAILED' ||
                state === 'DISCONNECTED' ||
                state == 'CONNECTED',
        });
        this.broadcastState();
        if (error != null &&
            Date.now() - this.bootTime > this.errorTriggerStartupDelay)
            this._Main.Twilio.sendError('CameraRunner', error);
        if (state == 'FAILED' || state == 'DISCONNECTED')
            console.warn(PREFIX, message !== null && message !== void 0 ? message : error);
        else
            console.log(PREFIX, message !== null && message !== void 0 ? message : error);
    };
    CameraRunner.prototype.startPollClock = function () {
        var _this = this;
        var poll = function () { return __awaiter(_this, void 0, void 0, function () {
            var data;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new Promise(function (resolve) {
                            _this.socket.emit('getStatus', function (response) {
                                return resolve(response);
                            });
                        })];
                    case 1:
                        data = _a.sent();
                        this.processStatus = data;
                        this._Main.Status.update(Status_1.StatusType.CameraProcess, exports.CameraProcessStateColors[this.processStatus.state], this.processStatus.message, {
                            reboot: this.processStatus.state === 'PROBLEM' ||
                                this.processStatus.state === 'STOPPED' ||
                                this.processStatus.state === 'RUNNING',
                        });
                        this.broadcastState();
                        return [2 /*return*/];
                }
            });
        }); };
        this.socket.on('simpleStatus', function (simpleStatus) {
            _this.processStatus.state = simpleStatus.state;
            _this.processStatus.message = simpleStatus.message;
            _this.processStatus.error = simpleStatus.error;
            _this._Main.Status.update(Status_1.StatusType.CameraProcess, exports.CameraProcessStateColors[_this.processStatus.state], _this.processStatus.message, {
                reboot: _this.processStatus.state === 'PROBLEM' ||
                    _this.processStatus.state === 'STOPPED' ||
                    _this.processStatus.state === 'RUNNING',
            });
            _this.broadcastState();
        });
        clearInterval(this.pollClock);
        this.pollClock = setInterval(function () { return poll(); }, this._Main.Config.cameraRunner.pollInterval);
        poll();
    };
    CameraRunner.prototype.reconnect = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        clearInterval(this.pollClock);
                        if (this.socket != null) {
                            this.socket.disconnect();
                            this.socket.close();
                            this.socket = null;
                        }
                        return [4 /*yield*/, (0, Utils_1.delay)(2000)];
                    case 1:
                        _a.sent();
                        this.message = 'Reconnecting in 10 seconds...';
                        this.broadcastState();
                        return [4 /*yield*/, (0, Utils_1.delay)(5000)];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this.connect()];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    CameraRunner.prototype.connect = function () {
        return __awaiter(this, void 0, void 0, function () {
            var ip, port;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.setInfo('Connecting...', null, 'CONNECTING');
                        return [4 /*yield*/, (0, Utils_1.delay)(1000)];
                    case 1:
                        _a.sent();
                        ip = this._Main.Config.cameraRunner.webSocket.ip;
                        port = this._Main.Config.cameraRunner.webSocket.port;
                        if (ip == null || port == null) {
                            return [2 /*return*/, this.setInfo('Connection problem', 'Camera Runner WebSocket IP or port is not configured.')];
                        }
                        this.socket = (0, socket_io_client_1.io)("ws://".concat(ip, ":").concat(port), {
                            reconnectionAttempts: 0,
                            reconnectionDelay: 2000,
                        });
                        this.socket.on('connect', function () {
                            _this._Main.Twilio.resetError('CameraRunner');
                            _this.setInfo('Connected', null, 'CONNECTED');
                            _this.startPollClock();
                        });
                        this.socket.on('disconnect', function () {
                            _this.setInfo('Disconnected', 'Camera Runner was disconnected unexpectedly', 'DISCONNECTED');
                            _this.reconnect();
                        });
                        this.socket.on('reconnect', function () {
                            _this.setInfo('Connected (reconnection)', null, 'CONNECTED');
                        });
                        this.socket.on('connect_error', function (err) {
                            _this.setInfo('Connection problem', "Connection error: ".concat(err));
                            _this.reconnect();
                        });
                        this.socket.on('error', function (err) {
                            _this.setInfo('Connection problem', "Socket error: ".concat(err));
                            _this.reconnect();
                        });
                        this.socket.on('reconnect_attempt', function () {
                            _this.setInfo('Reconnecting', null, 'CONNECTING');
                        });
                        this.socket.on('reconnect_failed', function () {
                            _this.setInfo('Connection problem', 'Reconnection failed');
                            _this.reconnect();
                        });
                        this.socket.on('close', function () {
                            _this.setInfo('Disconnected', null, 'DISCONNECTED');
                            _this.reconnect();
                        });
                        return [2 /*return*/];
                }
            });
        });
    };
    return CameraRunner;
}());
exports.CameraRunner = CameraRunner;
exports.CameraPCStateColors = {
    CONNECTED: Status_1.State.Green,
    DISCONNECTED: Status_1.State.Gray,
    CONNECTING: Status_1.State.Yellow,
    FAILED: Status_1.State.Red,
};
exports.CameraProcessStateColors = {
    RUNNING: Status_1.State.Green,
    STOPPED: Status_1.State.Gray,
    STARTING: Status_1.State.Yellow,
    PROBLEM: Status_1.State.Red,
};
//# sourceMappingURL=CameraRunner.js.map