"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
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;
    return g = { next: verb(0), "throw": verb(1), "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 (_) 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 };
    }
};
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;
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BoardsDataMenuUpdater = void 0;
var PQueue = require("p-queue");
var inversify_1 = require("inversify");
var command_1 = require("@theia/core/lib/common/command");
var menu_1 = require("@theia/core/lib/common/menu");
var disposable_1 = require("@theia/core/lib/common/disposable");
var boards_service_provider_1 = require("./boards-service-provider");
var protocol_1 = require("../../common/protocol");
var boards_data_store_1 = require("./boards-data-store");
var main_menu_manager_1 = require("../../common/main-menu-manager");
var arduino_menus_1 = require("../menu/arduino-menus");
var BoardsDataMenuUpdater = /** @class */ (function () {
    function BoardsDataMenuUpdater() {
        this.queue = new PQueue({ autoStart: true, concurrency: 1 });
        this.toDisposeOnBoardChange = new disposable_1.DisposableCollection();
    }
    BoardsDataMenuUpdater.prototype.onStart = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                this.updateMenuActions(this.boardsServiceClient.boardsConfig.selectedBoard);
                this.boardsDataStore.onChanged(function () { return _this.updateMenuActions(_this.boardsServiceClient.boardsConfig.selectedBoard); });
                this.boardsServiceClient.onBoardsConfigChanged(function (_a) {
                    var selectedBoard = _a.selectedBoard;
                    return _this.updateMenuActions(selectedBoard);
                });
                return [2 /*return*/];
            });
        });
    };
    BoardsDataMenuUpdater.prototype.updateMenuActions = function (selectedBoard) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                return [2 /*return*/, this.queue.add(function () { return __awaiter(_this, void 0, void 0, function () {
                        var fqbn_1, _a, configOptions, programmers, selectedProgrammer_1, boardsConfigMenuPath, _loop_1, this_1, _b, _c, _d, label, option, values, programmersMenuPath_1, label, _loop_2, this_2, programmers_1, programmers_1_1, programmer;
                        var e_1, _e, e_2, _f;
                        var _this = this;
                        return __generator(this, function (_g) {
                            switch (_g.label) {
                                case 0:
                                    this.toDisposeOnBoardChange.dispose();
                                    this.mainMenuManager.update();
                                    if (!selectedBoard) return [3 /*break*/, 2];
                                    fqbn_1 = selectedBoard.fqbn;
                                    if (!fqbn_1) return [3 /*break*/, 2];
                                    return [4 /*yield*/, this.boardsDataStore.getData(fqbn_1)];
                                case 1:
                                    _a = _g.sent(), configOptions = _a.configOptions, programmers = _a.programmers, selectedProgrammer_1 = _a.selectedProgrammer;
                                    if (configOptions.length) {
                                        boardsConfigMenuPath = __spread(arduino_menus_1.ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP, ['z01_boardsConfig']);
                                        _loop_1 = function (label, option, values) {
                                            var e_3, _a;
                                            var menuPath = __spread(boardsConfigMenuPath, ["" + option]);
                                            var commands = new Map();
                                            var _loop_3 = function (value) {
                                                var id = fqbn_1 + "-" + option + "--" + value.value;
                                                var command = { id: id };
                                                var selectedValue = value.value;
                                                var handler = {
                                                    execute: function () { return _this.boardsDataStore.selectConfigOption({ fqbn: fqbn_1, option: option, selectedValue: selectedValue }); },
                                                    isToggled: function () { return value.selected; }
                                                };
                                                commands.set(id, Object.assign(this_1.commandRegistry.registerCommand(command, handler), { label: value.label }));
                                            };
                                            try {
                                                for (var values_1 = (e_3 = void 0, __values(values)), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
                                                    var value = values_1_1.value;
                                                    _loop_3(value);
                                                }
                                            }
                                            catch (e_3_1) { e_3 = { error: e_3_1 }; }
                                            finally {
                                                try {
                                                    if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);
                                                }
                                                finally { if (e_3) throw e_3.error; }
                                            }
                                            this_1.menuRegistry.registerSubmenu(menuPath, label);
                                            this_1.toDisposeOnBoardChange.pushAll(__spread(commands.values(), [
                                                disposable_1.Disposable.create(function () { return arduino_menus_1.unregisterSubmenu(menuPath, _this.menuRegistry); })
                                            ], Array.from(commands.keys()).map(function (commandId, i) {
                                                var label = commands.get(commandId).label;
                                                _this.menuRegistry.registerMenuAction(menuPath, { commandId: commandId, order: "" + i, label: label });
                                                return disposable_1.Disposable.create(function () { return _this.menuRegistry.unregisterMenuAction(commandId); });
                                            })));
                                        };
                                        this_1 = this;
                                        try {
                                            for (_b = __values(configOptions.sort(protocol_1.ConfigOption.LABEL_COMPARATOR)), _c = _b.next(); !_c.done; _c = _b.next()) {
                                                _d = _c.value, label = _d.label, option = _d.option, values = _d.values;
                                                _loop_1(label, option, values);
                                            }
                                        }
                                        catch (e_1_1) { e_1 = { error: e_1_1 }; }
                                        finally {
                                            try {
                                                if (_c && !_c.done && (_e = _b.return)) _e.call(_b);
                                            }
                                            finally { if (e_1) throw e_1.error; }
                                        }
                                    }
                                    if (programmers.length) {
                                        programmersMenuPath_1 = __spread(arduino_menus_1.ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP, ['z02_programmers']);
                                        label = selectedProgrammer_1 ? "Programmer: \"" + selectedProgrammer_1.name + "\"" : 'Programmer';
                                        this.menuRegistry.registerSubmenu(programmersMenuPath_1, label);
                                        this.toDisposeOnBoardChange.push(disposable_1.Disposable.create(function () { return arduino_menus_1.unregisterSubmenu(programmersMenuPath_1, _this.menuRegistry); }));
                                        _loop_2 = function (programmer) {
                                            var id = programmer.id, name_1 = programmer.name;
                                            var command = { id: fqbn_1 + "-programmer--" + id };
                                            var handler = {
                                                execute: function () { return _this.boardsDataStore.selectProgrammer({ fqbn: fqbn_1, selectedProgrammer: programmer }); },
                                                isToggled: function () { return protocol_1.Programmer.equals(programmer, selectedProgrammer_1); }
                                            };
                                            this_2.menuRegistry.registerMenuAction(programmersMenuPath_1, { commandId: command.id, label: name_1 });
                                            this_2.commandRegistry.registerCommand(command, handler);
                                            this_2.toDisposeOnBoardChange.pushAll([
                                                disposable_1.Disposable.create(function () { return _this.commandRegistry.unregisterCommand(command); }),
                                                disposable_1.Disposable.create(function () { return _this.menuRegistry.unregisterMenuAction(command.id); })
                                            ]);
                                        };
                                        this_2 = this;
                                        try {
                                            for (programmers_1 = __values(programmers), programmers_1_1 = programmers_1.next(); !programmers_1_1.done; programmers_1_1 = programmers_1.next()) {
                                                programmer = programmers_1_1.value;
                                                _loop_2(programmer);
                                            }
                                        }
                                        catch (e_2_1) { e_2 = { error: e_2_1 }; }
                                        finally {
                                            try {
                                                if (programmers_1_1 && !programmers_1_1.done && (_f = programmers_1.return)) _f.call(programmers_1);
                                            }
                                            finally { if (e_2) throw e_2.error; }
                                        }
                                    }
                                    this.mainMenuManager.update();
                                    _g.label = 2;
                                case 2: return [2 /*return*/];
                            }
                        });
                    }); })];
            });
        });
    };
    __decorate([
        inversify_1.inject(command_1.CommandRegistry),
        __metadata("design:type", command_1.CommandRegistry)
    ], BoardsDataMenuUpdater.prototype, "commandRegistry", void 0);
    __decorate([
        inversify_1.inject(menu_1.MenuModelRegistry),
        __metadata("design:type", menu_1.MenuModelRegistry)
    ], BoardsDataMenuUpdater.prototype, "menuRegistry", void 0);
    __decorate([
        inversify_1.inject(main_menu_manager_1.MainMenuManager),
        __metadata("design:type", Object)
    ], BoardsDataMenuUpdater.prototype, "mainMenuManager", void 0);
    __decorate([
        inversify_1.inject(boards_data_store_1.BoardsDataStore),
        __metadata("design:type", boards_data_store_1.BoardsDataStore)
    ], BoardsDataMenuUpdater.prototype, "boardsDataStore", void 0);
    __decorate([
        inversify_1.inject(boards_service_provider_1.BoardsServiceProvider),
        __metadata("design:type", boards_service_provider_1.BoardsServiceProvider)
    ], BoardsDataMenuUpdater.prototype, "boardsServiceClient", void 0);
    BoardsDataMenuUpdater = __decorate([
        inversify_1.injectable()
    ], BoardsDataMenuUpdater);
    return BoardsDataMenuUpdater;
}());
exports.BoardsDataMenuUpdater = BoardsDataMenuUpdater;
//# sourceMappingURL=boards-data-menu-updater.js.map