"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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.CameraUnityStateColors = exports.UnityWebSocket = void 0;
var ws_1 = require("ws");
var Utils_1 = require("../Utils");
var Status_1 = require("../Status");
var PREFIX = '[Unity]';
var UnityWebSocket = /** @class */ (function () {
    function UnityWebSocket(Main) {
        this.state = 'DISCONNECTED';
        this.message = 'Waiting for process...';
        this.errorTriggerStartupDelay = 1000;
        this.parameters = {
            timelineWatching: false,
            timelineStanding: false,
            timelineProgress: 0,
            zedPath: '',
            zedReady: false,
            zedFPS: '-',
            outOfService: null,
            sliders: [],
            advancedSliders: [],
            // dataSliders: [],
            // dataAdvancedSliders: [],
            sensors: [],
        };
        this.disconnected = false;
        this.restartRequested = false;
        this._Main = Main;
        this.updateStatus();
    }
    UnityWebSocket.prototype.handle = function (command) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        switch (command) {
            case 'parameterValue':
                var sliderIndex = args[0];
                var percentage = args[1];
                this.setSliderValue(sliderIndex, percentage);
                break;
            case 'advancedParameterValue':
                var advSliderIndex = args[0];
                var advPercentage = args[1];
                this.setAdvancedSliderValue(advSliderIndex, advPercentage);
                break;
            // case 'dataParameterValue':
            // 	const dataSliderIndex: number = args[0];
            // 	const dataPercentage: number = args[1];
            // 	this.setDataSliderValue(dataSliderIndex, dataPercentage);
            // 	break;
            // case 'dataAdvancedParameterValue':
            // 	const dataAdvSliderIndex: number = args[0];
            // 	const dataAdvPercentage: number = args[1];
            // 	this.setDataAdvancedSliderValue(
            // 		dataAdvSliderIndex,
            // 		dataAdvPercentage,
            // 	);
            // 	break;
            case 'enableOutOfService':
                var enableCallback = args[0];
                if (typeof enableCallback !== 'function')
                    return;
                this.setOutOfService(true);
                enableCallback({ succeed: true });
                break;
            case 'disableOutOfService':
                var disableCallback = args[0];
                if (typeof disableCallback !== 'function')
                    return;
                this.setOutOfService(false);
                disableCallback({ succeed: true });
                break;
        }
    };
    UnityWebSocket.prototype.quitApplication = function () {
        if (this.socket == null || this.socket.readyState !== ws_1.WebSocket.OPEN)
            return;
        this.socket.send(JSON.stringify({
            type: 'quit_application',
        }));
    };
    UnityWebSocket.prototype.setSliderValue = function (sliderIndex, sliderValue) {
        if (this.socket == null || this.socket.readyState !== ws_1.WebSocket.OPEN)
            return;
        this.socket.send(JSON.stringify({
            type: 'set_slider_value',
            sliderIndex: sliderIndex,
            sliderValue: sliderValue,
        }));
        if (this.parameters.sliders[sliderIndex] == undefined)
            return;
        this.parameters.sliders[sliderIndex].outputValue = sliderValue;
        this.broadcastState();
    };
    UnityWebSocket.prototype.setAdvancedSliderValue = function (sliderIndex, sliderValue) {
        if (this.socket == null || this.socket.readyState !== ws_1.WebSocket.OPEN)
            return;
        this.socket.send(JSON.stringify({
            type: 'set_advanced_slider_value',
            sliderIndex: sliderIndex,
            sliderValue: sliderValue,
        }));
        if (this.parameters.advancedSliders[sliderIndex] == undefined)
            return;
        this.parameters.advancedSliders[sliderIndex].outputValue = sliderValue;
        this.broadcastState();
    };
    // setDataSliderValue(sliderIndex: number, sliderValue: number) {
    // 	if (this.socket == null || this.socket.readyState !== WebSocket.OPEN)
    // 		return;
    // 	this.socket.send(
    // 		JSON.stringify({
    // 			type: 'set_data_value',
    // 			sliderIndex,
    // 			sliderValue,
    // 		}),
    // 	);
    // 	if (this.parameters.dataSliders[sliderIndex] == undefined) return;
    // 	this.parameters.dataSliders[sliderIndex].outputValue = sliderValue;
    // 	this.broadcastState();
    // }
    // setDataAdvancedSliderValue(sliderIndex: number, sliderValue: number) {
    // 	if (this.socket == null || this.socket.readyState !== WebSocket.OPEN)
    // 		return;
    // 	this.socket.send(
    // 		JSON.stringify({
    // 			type: 'set_data_advanced_value',
    // 			sliderIndex,
    // 			sliderValue,
    // 		}),
    // 	);
    // 	if (this.parameters.dataAdvancedSliders[sliderIndex] == undefined)
    // 		return;
    // 	this.parameters.dataAdvancedSliders[sliderIndex].outputValue =
    // 		sliderValue;
    // 	this.broadcastState();
    // }
    UnityWebSocket.prototype.setOutOfService = function (state) {
        if (this.socket == null || this.socket.readyState !== ws_1.WebSocket.OPEN)
            return;
        this.socket.send(JSON.stringify({
            type: 'set_out_of_service',
            showOutOfService: state,
        }));
        this.parameters.outOfService = true;
        this.broadcastState();
    };
    UnityWebSocket.prototype.broadcastState = function () {
        this._Main.WebServer.socket.emit('unityWebSocketState', this.getState());
    };
    UnityWebSocket.prototype.updateStatus = function () {
        if (this.state != 'CONNECTED') {
            this._Main.Status.update(Status_1.StatusType.CameraUnityStream, exports.CameraUnityStateColors[this.state], this.message, {
                reboot: this.state === 'FAILED',
            });
        }
        else {
            var status_1 = !this.parameters.zedReady
                ? 'Waiting for ZED stream'
                : this.message;
            this._Main.Status.update(Status_1.StatusType.CameraUnityStream, this.parameters.zedReady ? Status_1.State.Green : Status_1.State.Yellow, status_1, {
                reboot: this.parameters.zedReady,
            });
        }
    };
    UnityWebSocket.prototype.setInfo = function (message, error, state) {
        if (state === void 0) { state = 'FAILED'; }
        this.message = message;
        this.error = error;
        this.state = state;
        this.updateStatus();
        this.broadcastState();
        if (error != null)
            this._Main.Twilio.sendError('UnityWebSocket', 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);
    };
    UnityWebSocket.prototype.stopFetchClocks = function () {
        clearInterval(this.heartbeatClock);
        clearInterval(this.calibrationImageClock);
    };
    UnityWebSocket.prototype.handleSocketMessage = function (data) {
        var _a;
        var message;
        try {
            message = JSON.parse(data.toString());
        }
        catch (error) {
            return;
        }
        // writeFileSync(
        // 	join(
        // 		this._Main.dataPath,
        // 		`tempdebug-${message.type}-${new Date().getTime()}.json`,
        // 	),
        // 	JSON.stringify(message, null, 4),
        // );
        switch (message.type) {
            case 'heartbeat_data':
                this.parameters.timelineWatching =
                    message.heartbeat.dataTimeline.isWatching;
                this.parameters.timelineStanding =
                    message.heartbeat.dataTimeline.isStanding;
                this.parameters.timelineProgress =
                    message.heartbeat.dataTimeline.timelineProgress;
                this.parameters.zedPath = "".concat(message.heartbeat.zedCamera.streamInputIP, ":").concat(message.heartbeat.zedCamera.streamInputPort);
                this.parameters.zedReady =
                    message.heartbeat.zedCamera.isZedReady;
                this.parameters.zedFPS = message.heartbeat.zedCamera.cameraFPS;
                this.parameters.outOfService =
                    (_a = message.heartbeat.showOutOfService) !== null && _a !== void 0 ? _a : false;
                this.parameters.sensors = message.heartbeat.dataSensors;
                this.parameters.sliders = message.heartbeat.dataSliders.map(function (slider) {
                    return __assign(__assign({}, slider), { decimalPlaces: (slider.min == 0 || slider.min == -1) &&
                            slider.max == 1
                            ? 2
                            : null });
                });
                this.parameters.advancedSliders =
                    message.heartbeat.dataAdvancedSliders.map(function (slider) {
                        return __assign(__assign({}, slider), { decimalPlaces: (slider.min == 0 || slider.min == -1) &&
                                slider.max == 1
                                ? 2
                                : null });
                    });
                this.updateStatus();
                this.broadcastState();
                break;
            case 'timeline_update':
                var playbackReady = message.value == 1;
                this._Main.Status.update(Status_1.StatusType.ReplayFunction, playbackReady ? Status_1.State.Green : Status_1.State.Yellow, playbackReady ? 'Playback ready' : 'Playback not ready');
                break;
            case 'response_camera_frame':
                this._Main.WebServer.Calibration.writeCalibrationImage(message.imageBase64);
                break;
        }
    };
    UnityWebSocket.prototype.disconnect = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.restartRequested = true;
                this.disconnected = true;
                if (this.socket != null) {
                    this.socket.close();
                    this.socket = null;
                }
                this.stopFetchClocks();
                this.setInfo('Waiting for process...', null, 'DISCONNECTED');
                return [2 /*return*/];
            });
        });
    };
    UnityWebSocket.prototype.reconnect = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.restartRequested)
                            return [2 /*return*/];
                        if (this.disconnected)
                            return [2 /*return*/];
                        this.restartRequested = true;
                        this.stopFetchClocks();
                        if (this.socket != null) {
                            this.socket.close();
                            this.socket = null;
                        }
                        return [4 /*yield*/, (0, Utils_1.delay)(2000)];
                    case 1:
                        _a.sent();
                        if (this.disconnected)
                            return [2 /*return*/];
                        this.message = "Reconnecting in 10 seconds...";
                        this.broadcastState();
                        return [4 /*yield*/, (0, Utils_1.delay)(10000)];
                    case 2:
                        _a.sent();
                        if (this.disconnected)
                            return [2 /*return*/];
                        return [4 /*yield*/, this.connect()];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    UnityWebSocket.prototype.connect = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.restartRequested = false;
                        this.disconnected = false;
                        this.stopFetchClocks();
                        this.setInfo("Connecting to ".concat(this._Main.Config.unity.webSocket.ip, ":").concat(this._Main.Config.unity.webSocket.port, "..."), null, 'CONNECTING');
                        return [4 /*yield*/, (0, Utils_1.delay)(1000)];
                    case 1:
                        _a.sent();
                        this.socket = new ws_1.WebSocket("ws://".concat(this._Main.Config.unity.webSocket.ip, ":").concat(this._Main.Config.unity.webSocket.port));
                        this.socket.on('error', function (error) {
                            if (_this.restartRequested)
                                return;
                            _this.setInfo('Connection error', "Could not connect: ".concat(error.message), 'FAILED');
                            _this.reconnect();
                        });
                        this.socket.on('open', function () {
                            _this.startFetchClocks();
                            _this._Main.Twilio.resetError('UnityWebSocket');
                            _this.setInfo('Connected', null, 'CONNECTED');
                        });
                        this.socket.on('close', function () {
                            if (_this._Main.UnityRunner.restartTriggered)
                                return;
                            if (_this.restartRequested)
                                return;
                            _this.setInfo('Disconnected', 'Unity was disconnected unexpectedly', 'FAILED');
                            _this.reconnect();
                        });
                        this.socket.on('message', function (data) { return _this.handleSocketMessage(data); });
                        return [2 /*return*/];
                }
            });
        });
    };
    UnityWebSocket.prototype.startFetchClocks = function () {
        var _this = this;
        this.socket.send(JSON.stringify({
            type: 'set_heartbeat_auto_send',
            autoSend: false,
        }));
        this.heartbeatClock = setInterval(function () {
            if (_this.socket == null ||
                _this.socket.readyState !== ws_1.WebSocket.OPEN)
                return;
            _this.socket.send(JSON.stringify({ type: 'request_heartbeat' }));
        }, this._Main.Config.unity.heartbeatInterval);
        this.calibrationImageClock = setInterval(function () {
            if (_this.socket == null ||
                _this.socket.readyState !== ws_1.WebSocket.OPEN)
                return;
            _this.socket.send(JSON.stringify({ type: 'request_camera_frame' }));
        }, this._Main.Config.unity.calibrationImageInterval);
    };
    UnityWebSocket.prototype.getState = function () {
        return {
            state: this.state,
            message: this.message,
            error: this.error,
            parameters: this.parameters,
        };
    };
    return UnityWebSocket;
}());
exports.UnityWebSocket = UnityWebSocket;
exports.CameraUnityStateColors = {
    CONNECTED: Status_1.State.Green,
    DISCONNECTED: Status_1.State.Gray,
    CONNECTING: Status_1.State.Yellow,
    FAILED: Status_1.State.Red,
};
//# sourceMappingURL=UnityWebSocket.js.map