"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.IncludeLibrary = void 0;
var PQueue = require("p-queue");
var inversify_1 = require("inversify");
var uri_1 = require("@theia/core/lib/common/uri");
var monaco_editor_1 = require("@theia/monaco/lib/browser/monaco-editor");
var browser_1 = require("@theia/editor/lib/browser");
var menu_1 = require("@theia/core/lib/common/menu");
var disposable_1 = require("@theia/core/lib/common/disposable");
var arduino_menus_1 = require("../menu/arduino-menus");
var protocol_1 = require("../../common/protocol");
var main_menu_manager_1 = require("../../common/main-menu-manager");
var library_list_widget_1 = require("../library/library-list-widget");
var boards_service_provider_1 = require("../boards/boards-service-provider");
var contribution_1 = require("./contribution");
var notification_center_1 = require("../notification-center");
var IncludeLibrary = /** @class */ (function (_super) {
    __extends(IncludeLibrary, _super);
    function IncludeLibrary() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.queue = new PQueue({ autoStart: true, concurrency: 1 });
        _this.toDispose = new disposable_1.DisposableCollection();
        return _this;
    }
    IncludeLibrary_1 = IncludeLibrary;
    IncludeLibrary.prototype.onStart = function () {
        var _this = this;
        this.updateMenuActions();
        this.boardsServiceClient.onBoardsConfigChanged(function () { return _this.updateMenuActions(); });
        this.notificationCenter.onLibraryInstalled(function () { return _this.updateMenuActions(); });
        this.notificationCenter.onLibraryUninstalled(function () { return _this.updateMenuActions(); });
    };
    IncludeLibrary.prototype.registerCommands = function (registry) {
        var _this = this;
        registry.registerCommand(IncludeLibrary_1.Commands.INCLUDE_LIBRARY, {
            execute: function (arg) { return __awaiter(_this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    if (protocol_1.LibraryPackage.is(arg)) {
                        this.includeLibrary(arg);
                    }
                    return [2 /*return*/];
                });
            }); }
        });
    };
    IncludeLibrary.prototype.updateMenuActions = function () {
        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 libraries, fqbn, _a, _b, _c, includeLibMenuPath, packageMenuPath, userMenuPath, libraries_1, libraries_1_1, library;
                        var e_1, _d;
                        var _this = this;
                        var _e;
                        return __generator(this, function (_f) {
                            switch (_f.label) {
                                case 0:
                                    this.toDispose.dispose();
                                    this.mainMenuManager.update();
                                    libraries = [];
                                    fqbn = (_e = this.boardsServiceClient.boardsConfig.selectedBoard) === null || _e === void 0 ? void 0 : _e.fqbn;
                                    if (!fqbn) return [3 /*break*/, 2];
                                    _b = (_a = libraries.push).apply;
                                    _c = [libraries];
                                    return [4 /*yield*/, this.libraryService.list({ fqbn: fqbn })];
                                case 1:
                                    _b.apply(_a, _c.concat([__spread.apply(void 0, [_f.sent()])]));
                                    _f.label = 2;
                                case 2:
                                    includeLibMenuPath = __spread(arduino_menus_1.ArduinoMenus.SKETCH__UTILS_GROUP, ['0_include']);
                                    this.menuRegistry.registerSubmenu(includeLibMenuPath, 'Include Library', { order: '1' });
                                    // `Manage Libraries...` group.
                                    this.menuRegistry.registerMenuAction(__spread(includeLibMenuPath, ['0_manage']), {
                                        commandId: library_list_widget_1.LibraryListWidget.WIDGET_ID + ":toggle",
                                        label: 'Manage Libraries...'
                                    });
                                    this.toDispose.push(disposable_1.Disposable.create(function () { return _this.menuRegistry.unregisterMenuAction({ commandId: library_list_widget_1.LibraryListWidget.WIDGET_ID + ":toggle" }); }));
                                    packageMenuPath = __spread(includeLibMenuPath, ['2_arduino']);
                                    userMenuPath = __spread(includeLibMenuPath, ['3_contributed']);
                                    try {
                                        for (libraries_1 = __values(libraries), libraries_1_1 = libraries_1.next(); !libraries_1_1.done; libraries_1_1 = libraries_1.next()) {
                                            library = libraries_1_1.value;
                                            this.toDispose.push(this.registerLibrary(library, library.location === protocol_1.LibraryLocation.USER ? userMenuPath : packageMenuPath));
                                        }
                                    }
                                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                                    finally {
                                        try {
                                            if (libraries_1_1 && !libraries_1_1.done && (_d = libraries_1.return)) _d.call(libraries_1);
                                        }
                                        finally { if (e_1) throw e_1.error; }
                                    }
                                    this.mainMenuManager.update();
                                    return [2 /*return*/];
                            }
                        });
                    }); })];
            });
        });
    };
    IncludeLibrary.prototype.registerLibrary = function (library, menuPath) {
        var _this = this;
        var commandId = "arduino-include-library--" + library.name + ":" + library.author;
        var command = { id: commandId };
        var handler = { execute: function () { return _this.commandRegistry.executeCommand(IncludeLibrary_1.Commands.INCLUDE_LIBRARY.id, library); } };
        var menuAction = { commandId: commandId, label: library.name };
        this.menuRegistry.registerMenuAction(menuPath, menuAction);
        return new disposable_1.DisposableCollection(this.commandRegistry.registerCommand(command, handler), disposable_1.Disposable.create(function () { return _this.menuRegistry.unregisterMenuAction(menuAction); }));
    };
    IncludeLibrary.prototype.includeLibrary = function (library) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var sketch, codeEditor, editor, widget, textModel, cursorState, eol, includes, text;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.sketchServiceClient.currentSketch()];
                    case 1:
                        sketch = _b.sent();
                        if (!sketch) {
                            return [2 /*return*/];
                        }
                        editor = (_a = this.editorManager.currentEditor) === null || _a === void 0 ? void 0 : _a.editor;
                        if (editor instanceof monaco_editor_1.MonacoEditor) {
                            if (sketch.additionalFileUris.some(function (uri) { return uri === editor.uri.toString(); })) {
                                codeEditor = editor.getControl();
                            }
                        }
                        if (!!codeEditor) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.editorManager.open(new uri_1.default(sketch.mainFileUri))];
                    case 2:
                        widget = _b.sent();
                        if (widget.editor instanceof monaco_editor_1.MonacoEditor) {
                            codeEditor = widget.editor.getControl();
                        }
                        _b.label = 3;
                    case 3:
                        if (!codeEditor) {
                            return [2 /*return*/];
                        }
                        textModel = codeEditor.getModel();
                        if (!textModel) {
                            return [2 /*return*/];
                        }
                        cursorState = codeEditor.getSelections() || [];
                        eol = textModel.getEOL();
                        includes = library.includes.slice();
                        includes.push(''); // For the trailing new line.
                        text = includes.map(function (include) { return include ? "#include <" + include + ">" : eol; }).join(eol);
                        textModel.pushStackElement(); // Start a fresh operation.
                        textModel.pushEditOperations(cursorState, [{
                                range: new monaco.Range(1, 1, 1, 1),
                                text: text,
                                forceMoveMarkers: true
                            }], function () { return cursorState; });
                        textModel.pushStackElement(); // Make it undoable.
                        return [2 /*return*/];
                }
            });
        });
    };
    var IncludeLibrary_1;
    __decorate([
        inversify_1.inject(contribution_1.CommandRegistry),
        __metadata("design:type", contribution_1.CommandRegistry)
    ], IncludeLibrary.prototype, "commandRegistry", void 0);
    __decorate([
        inversify_1.inject(menu_1.MenuModelRegistry),
        __metadata("design:type", menu_1.MenuModelRegistry)
    ], IncludeLibrary.prototype, "menuRegistry", void 0);
    __decorate([
        inversify_1.inject(main_menu_manager_1.MainMenuManager),
        __metadata("design:type", Object)
    ], IncludeLibrary.prototype, "mainMenuManager", void 0);
    __decorate([
        inversify_1.inject(browser_1.EditorManager),
        __metadata("design:type", browser_1.EditorManager)
    ], IncludeLibrary.prototype, "editorManager", void 0);
    __decorate([
        inversify_1.inject(notification_center_1.NotificationCenter),
        __metadata("design:type", notification_center_1.NotificationCenter)
    ], IncludeLibrary.prototype, "notificationCenter", void 0);
    __decorate([
        inversify_1.inject(boards_service_provider_1.BoardsServiceProvider),
        __metadata("design:type", boards_service_provider_1.BoardsServiceProvider)
    ], IncludeLibrary.prototype, "boardsServiceClient", void 0);
    __decorate([
        inversify_1.inject(protocol_1.LibraryService),
        __metadata("design:type", Object)
    ], IncludeLibrary.prototype, "libraryService", void 0);
    IncludeLibrary = IncludeLibrary_1 = __decorate([
        inversify_1.injectable()
    ], IncludeLibrary);
    return IncludeLibrary;
}(contribution_1.SketchContribution));
exports.IncludeLibrary = IncludeLibrary;
(function (IncludeLibrary) {
    var Commands;
    (function (Commands) {
        Commands.INCLUDE_LIBRARY = {
            id: 'arduino-include-library'
        };
    })(Commands = IncludeLibrary.Commands || (IncludeLibrary.Commands = {}));
})(IncludeLibrary = exports.IncludeLibrary || (exports.IncludeLibrary = {}));
exports.IncludeLibrary = IncludeLibrary;
//# sourceMappingURL=include-library.js.map