"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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.LibraryExamples = exports.BuiltInExamples = exports.Examples = void 0;
var PQueue = require("p-queue");
var inversify_1 = require("inversify");
var menu_1 = require("@theia/core/lib/common/menu");
var disposable_1 = require("@theia/core/lib/common/disposable");
var open_sketch_1 = require("./open-sketch");
var arduino_menus_1 = require("../menu/arduino-menus");
var main_menu_manager_1 = require("../../common/main-menu-manager");
var boards_service_provider_1 = require("../boards/boards-service-provider");
var examples_service_1 = require("../../common/protocol/examples-service");
var contribution_1 = require("./contribution");
var notification_center_1 = require("../notification-center");
var Examples = /** @class */ (function (_super) {
    __extends(Examples, _super);
    function Examples() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.toDispose = new disposable_1.DisposableCollection();
        return _this;
    }
    Examples.prototype.init = function () {
        var _this = this;
        this.boardsServiceClient.onBoardsConfigChanged(function (_a) {
            var selectedBoard = _a.selectedBoard;
            return _this.handleBoardChanged(selectedBoard === null || selectedBoard === void 0 ? void 0 : selectedBoard.fqbn);
        });
    };
    Examples.prototype.handleBoardChanged = function (fqbn) {
        // NOOP
    };
    Examples.prototype.registerMenus = function (registry) {
        try {
            // This is a hack the ensures the desired menu ordering! We cannot use https://github.com/eclipse-theia/theia/pull/8377 due to ATL-222.
            var index = arduino_menus_1.ArduinoMenus.FILE__EXAMPLES_SUBMENU.length - 1;
            var menuId = arduino_menus_1.ArduinoMenus.FILE__EXAMPLES_SUBMENU[index];
            var groupPath = index === 0 ? [] : arduino_menus_1.ArduinoMenus.FILE__EXAMPLES_SUBMENU.slice(0, index);
            var parent_1 = registry.findGroup(groupPath);
            var examples = new menu_1.CompositeMenuNode(menuId, '', { order: '4' });
            parent_1.addNode(examples);
        }
        catch (e) {
            console.error(e);
            console.warn('Could not patch menu ordering.');
        }
        // Registering the same submenu multiple times has no side-effect.
        // TODO: unregister submenu? https://github.com/eclipse-theia/theia/issues/7300
        registry.registerSubmenu(arduino_menus_1.ArduinoMenus.FILE__EXAMPLES_SUBMENU, 'Examples', { order: '4' });
    };
    Examples.prototype.registerRecursively = function (exampleContainer, menuPath, pushToDispose) {
        var e_1, _a;
        var _this = this;
        if (pushToDispose === void 0) { pushToDispose = new disposable_1.DisposableCollection(); }
        var label = exampleContainer.label, sketches = exampleContainer.sketches, children = exampleContainer.children;
        var submenuPath = __spread(menuPath, [label]);
        this.menuRegistry.registerSubmenu(submenuPath, label);
        children.forEach(function (child) { return _this.registerRecursively(child, submenuPath, pushToDispose); });
        var _loop_1 = function (sketch) {
            var uri = sketch.uri;
            var commandId = "arduino-open-example-" + submenuPath.join(':') + "--" + uri;
            var command = { id: commandId };
            var handler = {
                execute: function () { return __awaiter(_this, void 0, void 0, function () {
                    var sketch;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, this.sketchService.cloneExample(uri)];
                            case 1:
                                sketch = _a.sent();
                                this.commandService.executeCommand(open_sketch_1.OpenSketch.Commands.OPEN_SKETCH.id, sketch);
                                return [2 /*return*/];
                        }
                    });
                }); }
            };
            pushToDispose.push(this_1.commandRegistry.registerCommand(command, handler));
            this_1.menuRegistry.registerMenuAction(submenuPath, { commandId: commandId, label: sketch.name });
            pushToDispose.push(disposable_1.Disposable.create(function () { return _this.menuRegistry.unregisterMenuAction(command); }));
        };
        var this_1 = this;
        try {
            for (var sketches_1 = __values(sketches), sketches_1_1 = sketches_1.next(); !sketches_1_1.done; sketches_1_1 = sketches_1.next()) {
                var sketch = sketches_1_1.value;
                _loop_1(sketch);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (sketches_1_1 && !sketches_1_1.done && (_a = sketches_1.return)) _a.call(sketches_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
    };
    __decorate([
        inversify_1.inject(contribution_1.CommandRegistry),
        __metadata("design:type", contribution_1.CommandRegistry)
    ], Examples.prototype, "commandRegistry", void 0);
    __decorate([
        inversify_1.inject(contribution_1.MenuModelRegistry),
        __metadata("design:type", contribution_1.MenuModelRegistry)
    ], Examples.prototype, "menuRegistry", void 0);
    __decorate([
        inversify_1.inject(main_menu_manager_1.MainMenuManager),
        __metadata("design:type", Object)
    ], Examples.prototype, "menuManager", void 0);
    __decorate([
        inversify_1.inject(examples_service_1.ExamplesService),
        __metadata("design:type", Object)
    ], Examples.prototype, "examplesService", void 0);
    __decorate([
        inversify_1.inject(boards_service_provider_1.BoardsServiceProvider),
        __metadata("design:type", boards_service_provider_1.BoardsServiceProvider)
    ], Examples.prototype, "boardsServiceClient", void 0);
    __decorate([
        inversify_1.postConstruct(),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], Examples.prototype, "init", null);
    Examples = __decorate([
        inversify_1.injectable()
    ], Examples);
    return Examples;
}(contribution_1.SketchContribution));
exports.Examples = Examples;
var BuiltInExamples = /** @class */ (function (_super) {
    __extends(BuiltInExamples, _super);
    function BuiltInExamples() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    BuiltInExamples.prototype.onStart = function () {
        this.register(); // no `await`
    };
    BuiltInExamples.prototype.register = function () {
        return __awaiter(this, void 0, void 0, function () {
            var exampleContainers, e_2, exampleContainers_1, exampleContainers_1_1, container;
            var e_3, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.examplesService.builtIns()];
                    case 1:
                        exampleContainers = _b.sent();
                        return [3 /*break*/, 3];
                    case 2:
                        e_2 = _b.sent();
                        console.error('Could not initialize built-in examples.', e_2);
                        this.messageService.error('Could not initialize built-in examples.');
                        return [2 /*return*/];
                    case 3:
                        this.toDispose.dispose();
                        try {
                            for (exampleContainers_1 = __values(exampleContainers), exampleContainers_1_1 = exampleContainers_1.next(); !exampleContainers_1_1.done; exampleContainers_1_1 = exampleContainers_1.next()) {
                                container = exampleContainers_1_1.value;
                                this.registerRecursively(container, arduino_menus_1.ArduinoMenus.EXAMPLES__BUILT_IN_GROUP, this.toDispose);
                            }
                        }
                        catch (e_3_1) { e_3 = { error: e_3_1 }; }
                        finally {
                            try {
                                if (exampleContainers_1_1 && !exampleContainers_1_1.done && (_a = exampleContainers_1.return)) _a.call(exampleContainers_1);
                            }
                            finally { if (e_3) throw e_3.error; }
                        }
                        this.menuManager.update();
                        return [2 /*return*/];
                }
            });
        });
    };
    BuiltInExamples = __decorate([
        inversify_1.injectable()
    ], BuiltInExamples);
    return BuiltInExamples;
}(Examples));
exports.BuiltInExamples = BuiltInExamples;
var LibraryExamples = /** @class */ (function (_super) {
    __extends(LibraryExamples, _super);
    function LibraryExamples() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.queue = new PQueue({ autoStart: true, concurrency: 1 });
        return _this;
    }
    LibraryExamples.prototype.onStart = function () {
        var _this = this;
        this.register(); // no `await`
        this.notificationCenter.onLibraryInstalled(function () { return _this.register(); });
        this.notificationCenter.onLibraryUninstalled(function () { return _this.register(); });
    };
    LibraryExamples.prototype.handleBoardChanged = function (fqbn) {
        this.register(fqbn);
    };
    LibraryExamples.prototype.register = function (fqbn) {
        var _a;
        if (fqbn === void 0) { fqbn = (_a = this.boardsServiceClient.boardsConfig.selectedBoard) === null || _a === void 0 ? void 0 : _a.fqbn; }
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_b) {
                return [2 /*return*/, this.queue.add(function () { return __awaiter(_this, void 0, void 0, function () {
                        var _a, user, current, any, user_1, user_1_1, container, current_1, current_1_1, container, any_1, any_1_1, container;
                        var e_4, _b, e_5, _c, e_6, _d;
                        return __generator(this, function (_e) {
                            switch (_e.label) {
                                case 0:
                                    this.toDispose.dispose();
                                    if (!fqbn) {
                                        return [2 /*return*/];
                                    }
                                    return [4 /*yield*/, this.examplesService.installed({ fqbn: fqbn })];
                                case 1:
                                    _a = _e.sent(), user = _a.user, current = _a.current, any = _a.any;
                                    try {
                                        for (user_1 = __values(user), user_1_1 = user_1.next(); !user_1_1.done; user_1_1 = user_1.next()) {
                                            container = user_1_1.value;
                                            this.registerRecursively(container, arduino_menus_1.ArduinoMenus.EXAMPLES__USER_LIBS_GROUP, this.toDispose);
                                        }
                                    }
                                    catch (e_4_1) { e_4 = { error: e_4_1 }; }
                                    finally {
                                        try {
                                            if (user_1_1 && !user_1_1.done && (_b = user_1.return)) _b.call(user_1);
                                        }
                                        finally { if (e_4) throw e_4.error; }
                                    }
                                    try {
                                        for (current_1 = __values(current), current_1_1 = current_1.next(); !current_1_1.done; current_1_1 = current_1.next()) {
                                            container = current_1_1.value;
                                            this.registerRecursively(container, arduino_menus_1.ArduinoMenus.EXAMPLES__CURRENT_BOARD_GROUP, this.toDispose);
                                        }
                                    }
                                    catch (e_5_1) { e_5 = { error: e_5_1 }; }
                                    finally {
                                        try {
                                            if (current_1_1 && !current_1_1.done && (_c = current_1.return)) _c.call(current_1);
                                        }
                                        finally { if (e_5) throw e_5.error; }
                                    }
                                    try {
                                        for (any_1 = __values(any), any_1_1 = any_1.next(); !any_1_1.done; any_1_1 = any_1.next()) {
                                            container = any_1_1.value;
                                            this.registerRecursively(container, arduino_menus_1.ArduinoMenus.EXAMPLES__ANY_BOARD_GROUP, this.toDispose);
                                        }
                                    }
                                    catch (e_6_1) { e_6 = { error: e_6_1 }; }
                                    finally {
                                        try {
                                            if (any_1_1 && !any_1_1.done && (_d = any_1.return)) _d.call(any_1);
                                        }
                                        finally { if (e_6) throw e_6.error; }
                                    }
                                    this.menuManager.update();
                                    return [2 /*return*/];
                            }
                        });
                    }); })];
            });
        });
    };
    __decorate([
        inversify_1.inject(notification_center_1.NotificationCenter),
        __metadata("design:type", notification_center_1.NotificationCenter)
    ], LibraryExamples.prototype, "notificationCenter", void 0);
    LibraryExamples = __decorate([
        inversify_1.injectable()
    ], LibraryExamples);
    return LibraryExamples;
}(Examples));
exports.LibraryExamples = LibraryExamples;
//# sourceMappingURL=examples.js.map