"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.DashboardUnity = void 0;
var morphux_1 = require("morphux");
var utils_1 = require("./utils");
var DashboardUnity = /** @class */ (function () {
    function DashboardUnity(Main) {
        this.container = document.querySelector('.ntsh_dashboard-unity');
        this.processStatus = document.querySelector('.ntsh_dashboard-unity-processstatus');
        this.processInfo = document.querySelector('.ntsh_dashboard-unity-processinfo');
        this.restartButton = document.querySelector('.ntsh_dashboard-unity-restart');
        this.startButton = document.querySelector('.ntsh_dashboard-unity-start');
        this.stopButton = document.querySelector('.ntsh_dashboard-unity-stop');
        this.uptimeInfo = document.querySelector('.ntsh_dashboard-unity-uptime');
        this.webSocketStatus = document.querySelector('.ntsh_dashboard-unity-websocketstatus');
        this.webSocketInfo = document.querySelector('.ntsh_dashboard-unity-websocketinfo');
        this.outOfServiceStatus = document.querySelector('.ntsh_dashboard-unity-outofservicestatus');
        this.outOfServiceInfo = document.querySelector('.ntsh_dashboard-unity-outofserviceinfo');
        this.enableOutOfServiceButton = document.querySelector('.ntsh_dashboard-unity-enableoutofservice');
        this.disableOutOfServiceButton = document.querySelector('.ntsh_dashboard-unity-disableoutofservice');
        this.zedStreamStatus = document.querySelector('.ntsh_dashboard-unity-zedstreamstatus');
        this.zedStreamInfo = document.querySelector('.ntsh_dashboard-unity-zedstreaminfo');
        this.zedStreamFps = document.querySelector('.ntsh_dashboard-unity-zedstreamfps');
        this.zedStreamPath = document.querySelector('.ntsh_dashboard-unity-zedstreampath');
        this.timelineWatching = document.querySelector('.ntsh_dashboard-unity-timeline-watching');
        this.timelineStanding = document.querySelector('.ntsh_dashboard-unity-timeline-standing');
        this.timelineProgress = document.querySelector('.ntsh_dashboard-unity-timeline-progress');
        this.parametersTable = document.querySelector('.ntsh_dashboard-unity-parameters');
        this.advancedParametersTable = document.querySelector('.ntsh_dashboard-unity-advancedparameters');
        this.sensorsTable = document.querySelector('.ntsh_dashboard-unity-sensors');
        this.errorContainer = document.querySelector('.ntsh_dashboard-unity-error');
        this.errorText = document.querySelector('.ntsh_dashboard-unity-errortext');
        this._Main = Main;
        this.registerListeners();
    }
    DashboardUnity.prototype.updateRunnerState = function (state) {
        var _a, _b;
        // ----------- Process -----------
        if (state.state != 'RUNNING') {
            state.startTime = -1;
            this.restartButton.style.display = 'none';
            this.stopButton.style.display = 'none';
        }
        else {
            this.restartButton.style.display = 'flex';
            this.stopButton.style.display = 'flex';
        }
        this.startButton.style.display =
            state.state == 'STOPPED' ? 'flex' : 'none';
        (0, utils_1.setStatusState)(this.processStatus, {
            RUNNING: 'green',
            STOPPED: 'gray',
            STARTING: 'yellow',
            PROBLEM: 'red',
        }[state.state]);
        this.processInfo.innerText = (_a = state.message) !== null && _a !== void 0 ? _a : '';
        // ----------- Uptime -----------
        var uptimeSeconds = state.startTime == -1 ? -1 : (Date.now() - state.startTime) / 1000;
        this.uptimeInfo.innerText = (0, utils_1.formatUptime)(uptimeSeconds);
        // ----------- Error -----------
        if (((_b = state === null || state === void 0 ? void 0 : state.error) !== null && _b !== void 0 ? _b : '').trim().length > 0)
            this.runnerError = state.error;
        else
            this.runnerError = null;
        this.updateError();
        this._Main.Logs.setUnityLogs(state.output.current);
    };
    DashboardUnity.prototype.updateWebSocketState = function (state) {
        var _a, _b;
        // ----------- WebSocket -----------
        (0, utils_1.setStatusState)(this.webSocketStatus, {
            CONNECTING: 'yellow',
            CONNECTED: 'green',
            DISCONNECTED: 'gray',
            FAILED: 'red',
        }[state.state]);
        this.webSocketInfo.innerText = (_a = state.message) !== null && _a !== void 0 ? _a : '';
        // ----------- Out of Service -----------
        (0, utils_1.setStatusState)(this.outOfServiceStatus, state.parameters.outOfService == null
            ? 'gray'
            : state.parameters.outOfService
                ? 'red'
                : 'green');
        this.outOfServiceInfo.innerText =
            state.parameters.outOfService == null
                ? ''
                : state.parameters.outOfService
                    ? 'Out of Service'
                    : 'Operational';
        this.enableOutOfServiceButton.style.display =
            state.parameters.outOfService == null ||
                state.parameters.outOfService
                ? 'none'
                : 'flex';
        this.disableOutOfServiceButton.style.display =
            state.parameters.outOfService &&
                state.parameters.outOfService != null
                ? 'flex'
                : 'none';
        // ----------- ZED Stream -----------
        (0, utils_1.setStatusState)(this.zedStreamStatus, state.parameters.zedReady ? 'green' : 'red');
        this.zedStreamInfo.innerText = state.parameters.zedReady
            ? "Connected to ".concat(state.parameters.zedPath)
            : 'Not ready';
        this.zedStreamFps.innerText =
            state.parameters.zedFPS == '-' ? '' : state.parameters.zedFPS;
        // ----------- Timeline -----------
        this.timelineWatching.innerText = state.parameters.timelineWatching
            ? 'Yes'
            : 'No';
        this.timelineStanding.innerText = state.parameters.timelineStanding
            ? 'Yes'
            : 'No';
        (0, utils_1.setProgressState)(this.timelineProgress, Math.round(state.parameters.timelineProgress * 100), 0, 100, '%');
        // ----------- Parameters -----------
        this.renderParameterSliders(state.state == 'CONNECTED' ? state.parameters.sliders : []);
        this.renderAdvancedParameterSliders(state.state == 'CONNECTED' ? state.parameters.advancedSliders : []);
        this.renderParameterSensors(state.state == 'CONNECTED' ? state.parameters.sensors : []);
        // ----------- Error -----------
        if (((_b = state === null || state === void 0 ? void 0 : state.error) !== null && _b !== void 0 ? _b : '').trim().length > 0)
            this.webSocketError = state.error;
        else
            this.webSocketError = null;
        this.updateError();
    };
    DashboardUnity.prototype.renderParameterSliders = function (sliders) {
        var _this = this;
        var existingSliders = this.parametersTable.querySelectorAll('.ntsh_dashboard-unity-parameter-row');
        if (existingSliders.length !== sliders.length) {
            this.parametersTable.innerHTML = '';
            if (sliders.length === 0) {
                var row = (0, morphux_1.ce)('tr');
                var cell = (0, morphux_1.ce)('td');
                cell.appendChild((0, morphux_1.ce)('div', ['mux_text', 'ntsh_dashboard-unity-parameters-loading'], null, 'Waiting for Unity...'));
                row.appendChild(cell);
                this.parametersTable.appendChild(row);
            }
            else
                sliders.forEach(function (slider) {
                    var _a, _b;
                    var multiplierFactor = (_a = slider.visualMultiplier) !== null && _a !== void 0 ? _a : 1;
                    var decimalPlacesFactor = Math.pow(10, ((_b = slider.decimalPlaces) !== null && _b !== void 0 ? _b : 0));
                    var value = Math.round(slider.outputValue *
                        multiplierFactor *
                        decimalPlacesFactor) / decimalPlacesFactor;
                    var row = (0, morphux_1.ce)('tr', 'ntsh_dashboard-unity-parameter-row');
                    var nameCell = (0, morphux_1.ce)('td');
                    nameCell.appendChild((0, morphux_1.ce)('div', 'mux_text', null, slider.sliderName));
                    row.appendChild(nameCell);
                    var progressCell = (0, morphux_1.ce)('td', 'no-service');
                    progressCell.appendChild((0, utils_1.createProgress)(value, slider.min * multiplierFactor, slider.max * multiplierFactor, slider.unit));
                    row.appendChild(progressCell);
                    var sliderCell = (0, morphux_1.ce)('td', 'only-service');
                    var sliderProgress = (0, utils_1.createProgress)(value, slider.min * multiplierFactor, slider.max * multiplierFactor, slider.unit);
                    var sliderValue = sliderProgress.querySelector('.ntsh_progress-value');
                    sliderValue.classList.add('mux_resizer');
                    sliderCell.appendChild(sliderProgress);
                    var resizer = new morphux_1.MorphComponent.Resizer({
                        existingContainer: sliderValue,
                        direction: 'right',
                        relative: true,
                        min: 0,
                        max: function () { return sliderProgress.clientWidth; },
                    });
                    var lastValue = -1;
                    resizer.on('resized', function (size) {
                        var percentage = Math.round((size / sliderProgress.clientWidth) * 100) / 100;
                        var actualValue = slider.min + percentage * (slider.max - slider.min);
                        if (actualValue === lastValue)
                            return;
                        lastValue = actualValue;
                        _this._Main.socket.emit('unityWebSocket', 'parameterValue', slider.sliderIndex, actualValue);
                        (0, utils_1.setProgressState)(sliderProgress, Math.round(actualValue *
                            multiplierFactor *
                            decimalPlacesFactor) / decimalPlacesFactor, slider.min * multiplierFactor, slider.max * multiplierFactor, slider.unit);
                    });
                    row.appendChild(sliderCell);
                    _this.parametersTable.appendChild(row);
                });
        }
        else {
            existingSliders.forEach(function (row, index) {
                var _a, _b;
                var slider = sliders[index];
                var multiplierFactor = (_a = slider.visualMultiplier) !== null && _a !== void 0 ? _a : 1;
                var decimalPlacesFactor = Math.pow(10, ((_b = slider.decimalPlaces) !== null && _b !== void 0 ? _b : 0));
                var value = Math.round(slider.outputValue *
                    multiplierFactor *
                    decimalPlacesFactor) / decimalPlacesFactor;
                var progressElement = row.querySelector('.no-service .ntsh_progress');
                (0, utils_1.setProgressState)(progressElement, value, slider.min * multiplierFactor, slider.max * multiplierFactor, slider.unit);
                var sliderElement = row.querySelector('.only-service .ntsh_progress');
                if (sliderElement.querySelector('.mux_resizer-moving') == null)
                    (0, utils_1.setProgressState)(sliderElement, value, slider.min * multiplierFactor, slider.max * multiplierFactor, slider.unit);
            });
        }
    };
    DashboardUnity.prototype.renderAdvancedParameterSliders = function (sliders) {
        var _this = this;
        var existingSliders = this.advancedParametersTable.querySelectorAll('.ntsh_dashboard-unity-parameter-row');
        if (existingSliders.length !== sliders.length) {
            this.advancedParametersTable.innerHTML = '';
            if (sliders.length === 0) {
                var row = (0, morphux_1.ce)('tr');
                var cell = (0, morphux_1.ce)('td');
                cell.appendChild((0, morphux_1.ce)('div', ['mux_text', 'ntsh_dashboard-unity-parameters-loading'], null, 'Waiting for Unity...'));
                row.appendChild(cell);
                this.advancedParametersTable.appendChild(row);
            }
            else
                sliders.forEach(function (slider) {
                    var _a, _b;
                    var multiplierFactor = (_a = slider.visualMultiplier) !== null && _a !== void 0 ? _a : 1;
                    var decimalPlacesFactor = Math.pow(10, ((_b = slider.decimalPlaces) !== null && _b !== void 0 ? _b : 0));
                    var value = Math.round(slider.outputValue *
                        multiplierFactor *
                        decimalPlacesFactor) / decimalPlacesFactor;
                    var row = (0, morphux_1.ce)('tr', 'ntsh_dashboard-unity-parameter-row');
                    var nameCell = (0, morphux_1.ce)('td');
                    nameCell.appendChild((0, morphux_1.ce)('div', 'mux_text', null, slider.sliderName));
                    row.appendChild(nameCell);
                    var progressCell = (0, morphux_1.ce)('td', 'no-service');
                    progressCell.appendChild((0, utils_1.createProgress)(value, slider.min * multiplierFactor, slider.max * multiplierFactor, slider.unit));
                    row.appendChild(progressCell);
                    var sliderCell = (0, morphux_1.ce)('td', 'only-service');
                    var sliderProgress = (0, utils_1.createProgress)(value, slider.min * multiplierFactor, slider.max * multiplierFactor, slider.unit);
                    var sliderValue = sliderProgress.querySelector('.ntsh_progress-value');
                    sliderValue.classList.add('mux_resizer');
                    sliderCell.appendChild(sliderProgress);
                    var resizer = new morphux_1.MorphComponent.Resizer({
                        existingContainer: sliderValue,
                        direction: 'right',
                        relative: true,
                        min: 0,
                        max: function () { return sliderProgress.clientWidth; },
                    });
                    var lastValue = -1;
                    resizer.on('resized', function (size) {
                        var percentage = Math.round((size / sliderProgress.clientWidth) * 100) / 100;
                        var actualValue = slider.min + percentage * (slider.max - slider.min);
                        if (actualValue === lastValue)
                            return;
                        lastValue = actualValue;
                        _this._Main.socket.emit('unityWebSocket', 'advancedParameterValue', slider.sliderIndex, actualValue);
                        (0, utils_1.setProgressState)(sliderProgress, Math.round(actualValue *
                            multiplierFactor *
                            decimalPlacesFactor) / decimalPlacesFactor, slider.min * multiplierFactor, slider.max * multiplierFactor, slider.unit);
                    });
                    row.appendChild(sliderCell);
                    _this.advancedParametersTable.appendChild(row);
                });
        }
        else {
            existingSliders.forEach(function (row, index) {
                var _a, _b;
                var slider = sliders[index];
                var multiplierFactor = (_a = slider.visualMultiplier) !== null && _a !== void 0 ? _a : 1;
                var decimalPlacesFactor = Math.pow(10, ((_b = slider.decimalPlaces) !== null && _b !== void 0 ? _b : 0));
                var value = Math.round(slider.outputValue *
                    multiplierFactor *
                    decimalPlacesFactor) / decimalPlacesFactor;
                var progressElement = row.querySelector('.no-service .ntsh_progress');
                (0, utils_1.setProgressState)(progressElement, value, slider.min * multiplierFactor, slider.max * multiplierFactor, slider.unit);
                var sliderElement = row.querySelector('.only-service .ntsh_progress');
                if (sliderElement.querySelector('.mux_resizer-moving') == null)
                    (0, utils_1.setProgressState)(sliderElement, value, slider.min * multiplierFactor, slider.max * multiplierFactor, slider.unit);
            });
        }
    };
    DashboardUnity.prototype.renderParameterSensors = function (sensors) {
        var _this = this;
        var existingSensors = this.sensorsTable.querySelectorAll('.ntsh_dashboard-unity-sensor-row');
        if (existingSensors.length !== sensors.length) {
            this.sensorsTable.innerHTML = '';
            if (sensors.length === 0) {
                var row = (0, morphux_1.ce)('tr');
                var cell = (0, morphux_1.ce)('td');
                cell.appendChild((0, morphux_1.ce)('div', ['mux_text', 'ntsh_dashboard-unity-sensors-loading'], null, 'Waiting for Unity...'));
                row.appendChild(cell);
                this.sensorsTable.appendChild(row);
            }
            else
                sensors.forEach(function (sensor) {
                    var row = (0, morphux_1.ce)('tr', 'ntsh_dashboard-unity-sensor-row');
                    var nameCell = (0, morphux_1.ce)('td');
                    nameCell.appendChild((0, morphux_1.ce)('div', 'mux_text', null, sensor.deviceName));
                    row.appendChild(nameCell);
                    var progressCell = (0, morphux_1.ce)('td');
                    progressCell.appendChild((0, utils_1.createProgress)(Math.round(sensor.outputValue * 100), 0, 100, '%'));
                    row.appendChild(progressCell);
                    _this.sensorsTable.appendChild(row);
                });
        }
        else {
            existingSensors.forEach(function (row, index) {
                var value = sensors[index].outputValue;
                var progressElement = row.querySelector('.ntsh_progress');
                (0, utils_1.setProgressState)(progressElement, Math.round(value * 100), 0, 100, '%');
            });
        }
    };
    DashboardUnity.prototype.updateError = function () {
        var errors = [];
        if (this.runnerError != null)
            errors.push(this.runnerError);
        if (this.webSocketError != null)
            errors.push(this.webSocketError);
        if (errors.length > 0) {
            this.errorText.innerText = errors.join('\n');
            this.errorContainer.style.display = 'block';
        }
        else {
            this.errorContainer.style.display = 'none';
            this.errorText.innerText = '';
        }
    };
    DashboardUnity.prototype.registerListeners = function () {
        var _this = this;
        this._Main.socket.on('unityRunnerState', function (state) {
            return _this.updateRunnerState(state);
        });
        this._Main.socket.on('unityWebSocketState', function (state) { return _this.updateWebSocketState(state); });
        this.restartButton.addEventListener('click', function () { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.executeCommand('restart', 'Are you sure you want to restart the Unity Runner process?');
                return [2 /*return*/];
            });
        }); });
        this.startButton.addEventListener('click', function () { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.executeCommand('start', 'Are you sure you want to start the Unity Runner process?');
                return [2 /*return*/];
            });
        }); });
        this.stopButton.addEventListener('click', function () { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.executeCommand('stop', 'Are you sure you want to stop the Unity Runner process?');
                return [2 /*return*/];
            });
        }); });
        this.enableOutOfServiceButton.addEventListener('click', function () { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.executeCommand('enableOutOfService', 'Are you sure you want to set the installation to "Out of Service"?', 'unityWebSocket');
                return [2 /*return*/];
            });
        }); });
        this.disableOutOfServiceButton.addEventListener('click', function () { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.executeCommand('disableOutOfService', 'Are you sure you want to set the installation to "Operational"?', 'unityWebSocket');
                return [2 /*return*/];
            });
        }); });
    };
    DashboardUnity.prototype.executeCommand = function (command_1, message_1) {
        return __awaiter(this, arguments, void 0, function (command, message, type) {
            var confirmed;
            if (type === void 0) { type = 'unityRunner'; }
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, morphux_1.MorphFeature.Confirm({
                            title: 'Are you sure?',
                            message: message,
                        })];
                    case 1:
                        confirmed = _a.sent();
                        if (!confirmed)
                            return [2 /*return*/];
                        morphux_1.MorphFeature.Loader({
                            active: true,
                            message: "Dispatching command...",
                        });
                        this._Main.socket.emit(type, command, function (response) {
                            morphux_1.MorphFeature.Loader({ active: false });
                            if (!response.succeed)
                                return morphux_1.MorphFeature.Alert({
                                    title: 'Error',
                                    message: response.message,
                                });
                            morphux_1.MorphFeature.Notification({
                                level: 'success',
                                message: "Dispatched command",
                            });
                        });
                        return [2 /*return*/];
                }
            });
        });
    };
    return DashboardUnity;
}());
exports.DashboardUnity = DashboardUnity;
//# sourceMappingURL=dashboard.unity.js.map