"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 __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 __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.AvailableBoard = exports.BoardsServiceProvider = void 0;
var inversify_1 = require("inversify");
var event_1 = require("@theia/core/lib/common/event");
var logger_1 = require("@theia/core/lib/common/logger");
var message_service_1 = require("@theia/core/lib/common/message-service");
var storage_service_1 = require("@theia/core/lib/browser/storage-service");
var protocol_1 = require("../../common/protocol");
var boards_config_1 = require("./boards-config");
var utils_1 = require("../../common/utils");
var comparers_1 = require("../theia/monaco/comparers");
var notification_center_1 = require("../notification-center");
var core_1 = require("@theia/core");
var arduino_commands_1 = require("../arduino-commands");
var BoardsServiceProvider = /** @class */ (function () {
    function BoardsServiceProvider() {
        this.onBoardsConfigChangedEmitter = new event_1.Emitter();
        this.onAvailableBoardsChangedEmitter = new event_1.Emitter();
        /**
         * Used for the auto-reconnecting. Sometimes, the attached board gets disconnected after uploading something to it.
         * It happens with certain boards on Windows. For example, the `MKR1000` boards is selected on post `COM5` on Windows,
         * perform an upload, the board automatically disconnects and reconnects, but on another port, `COM10`.
         * We have to listen on such changes and auto-reconnect the same board on another port.
         * See: https://arduino.slack.com/archives/CJJHJCJSJ/p1568645417013000?thread_ts=1568640504.009400&cid=CJJHJCJSJ
         */
        this.latestValidBoardsConfig = undefined;
        this.latestBoardsConfig = undefined;
        this._boardsConfig = {};
        this._attachedBoards = []; // This does not contain the `Unknown` boards. They're visible from the available ports only.
        this._availablePorts = [];
        this._availableBoards = [];
        /**
         * Unlike `onAttachedBoardsChanged` this even fires when the user modifies the selected board in the IDE.\
         * This even also fires, when the boards package was not available for the currently selected board,
         * and the user installs the board package. Note: installing a board package will set the `fqbn` of the
         * currently selected board.\
         * This even also emitted when the board package for the currently selected board was uninstalled.
         */
        this.onBoardsConfigChanged = this.onBoardsConfigChangedEmitter.event;
        this.onAvailableBoardsChanged = this.onAvailableBoardsChangedEmitter.event;
    }
    BoardsServiceProvider.prototype.onStart = function () {
        var _this = this;
        this.notificationCenter.onAttachedBoardsChanged(this.notifyAttachedBoardsChanged.bind(this));
        this.notificationCenter.onPlatformInstalled(this.notifyPlatformInstalled.bind(this));
        this.notificationCenter.onPlatformUninstalled(this.notifyPlatformUninstalled.bind(this));
        Promise.all([
            this.boardsService.getAttachedBoards(),
            this.boardsService.getAvailablePorts(),
            this.loadState()
        ]).then(function (_a) {
            var _b = __read(_a, 2), attachedBoards = _b[0], availablePorts = _b[1];
            _this._attachedBoards = attachedBoards;
            _this._availablePorts = availablePorts;
            _this.reconcileAvailableBoards().then(function () { return _this.tryReconnect(); });
        });
    };
    BoardsServiceProvider.prototype.notifyAttachedBoardsChanged = function (event) {
        var _this = this;
        if (!protocol_1.AttachedBoardsChangeEvent.isEmpty(event)) {
            this.logger.info('Attached boards and available ports changed:');
            this.logger.info(protocol_1.AttachedBoardsChangeEvent.toString(event));
            this.logger.info("------------------------------------------");
        }
        this._attachedBoards = event.newState.boards;
        this._availablePorts = event.newState.ports;
        this.reconcileAvailableBoards().then(function () { return _this.tryReconnect(); });
    };
    BoardsServiceProvider.prototype.notifyPlatformInstalled = function (event) {
        var _this = this;
        this.logger.info('Boards package installed: ', JSON.stringify(event));
        var selectedBoard = this.boardsConfig.selectedBoard;
        var _a = event.item, installedVersion = _a.installedVersion, id = _a.id;
        if (selectedBoard) {
            var installedBoard = event.item.boards.find(function (_a) {
                var name = _a.name;
                return name === selectedBoard.name;
            });
            if (installedBoard && (!selectedBoard.fqbn || selectedBoard.fqbn === installedBoard.fqbn)) {
                this.logger.info("Board package " + id + "[" + installedVersion + "] was installed. Updating the FQBN of the currently selected " + selectedBoard.name + " board. [FQBN: " + installedBoard.fqbn + "]");
                this.boardsConfig = __assign(__assign({}, this.boardsConfig), { selectedBoard: installedBoard });
                return;
            }
            // The board name can change after install.
            // This logic handles it "gracefully" by unselecting the board, so that we can avoid no FQBN is set error.
            // https://github.com/arduino/arduino-cli/issues/620
            // https://github.com/arduino/arduino-pro-ide/issues/374
            if (protocol_1.BoardWithPackage.is(selectedBoard) && selectedBoard.packageId === event.item.id && !installedBoard) {
                this.messageService.warn("Could not find previously selected board '" + selectedBoard.name + "' in installed platform '" + event.item.name + "'. Please manually reselect the board you want to use. Do you want to reselect it now?", 'Reselect later', 'Yes').then(function (answer) { return __awaiter(_this, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        if (answer === 'Yes') {
                            this.commandService.executeCommand(arduino_commands_1.ArduinoCommands.OPEN_BOARDS_DIALOG.id, selectedBoard.name);
                        }
                        return [2 /*return*/];
                    });
                }); });
                this.boardsConfig = {};
                return;
            }
            // Trigger a board re-set. See: https://github.com/arduino/arduino-cli/issues/954
            // E.g: install `adafruit:avr`, then select `adafruit:avr:adafruit32u4` board, and finally install the required `arduino:avr`
            this.boardsConfig = this.boardsConfig;
        }
    };
    BoardsServiceProvider.prototype.notifyPlatformUninstalled = function (event) {
        this.logger.info('Boards package uninstalled: ', JSON.stringify(event));
        var selectedBoard = this.boardsConfig.selectedBoard;
        if (selectedBoard && selectedBoard.fqbn) {
            var uninstalledBoard = event.item.boards.find(function (_a) {
                var name = _a.name;
                return name === selectedBoard.name;
            });
            if (uninstalledBoard && uninstalledBoard.fqbn === selectedBoard.fqbn) {
                this.logger.info("Board package " + event.item.id + " was uninstalled. Discarding the FQBN of the currently selected " + selectedBoard.name + " board.");
                var selectedBoardWithoutFqbn = {
                    name: selectedBoard.name
                    // No FQBN
                };
                this.boardsConfig = __assign(__assign({}, this.boardsConfig), { selectedBoard: selectedBoardWithoutFqbn });
            }
        }
    };
    BoardsServiceProvider.prototype.tryReconnect = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, _b, board, _c, _d, board;
            var e_1, _e, e_2, _f;
            return __generator(this, function (_g) {
                if (this.latestValidBoardsConfig && !this.canUploadTo(this.boardsConfig)) {
                    try {
                        for (_a = __values(this.availableBoards.filter(function (_a) {
                            var state = _a.state;
                            return state !== AvailableBoard.State.incomplete;
                        })), _b = _a.next(); !_b.done; _b = _a.next()) {
                            board = _b.value;
                            if (this.latestValidBoardsConfig.selectedBoard.fqbn === board.fqbn
                                && this.latestValidBoardsConfig.selectedBoard.name === board.name
                                && protocol_1.Port.sameAs(this.latestValidBoardsConfig.selectedPort, board.port)) {
                                this.boardsConfig = this.latestValidBoardsConfig;
                                return [2 /*return*/, true];
                            }
                        }
                    }
                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                    finally {
                        try {
                            if (_b && !_b.done && (_e = _a.return)) _e.call(_a);
                        }
                        finally { if (e_1) throw e_1.error; }
                    }
                    try {
                        // If we could not find an exact match, we compare the board FQBN-name pairs and ignore the port, as it might have changed.
                        // See documentation on `latestValidBoardsConfig`.
                        for (_c = __values(this.availableBoards.filter(function (_a) {
                            var state = _a.state;
                            return state !== AvailableBoard.State.incomplete;
                        })), _d = _c.next(); !_d.done; _d = _c.next()) {
                            board = _d.value;
                            if (this.latestValidBoardsConfig.selectedBoard.fqbn === board.fqbn
                                && this.latestValidBoardsConfig.selectedBoard.name === board.name) {
                                this.boardsConfig = __assign(__assign({}, this.latestValidBoardsConfig), { selectedPort: board.port });
                                return [2 /*return*/, true];
                            }
                        }
                    }
                    catch (e_2_1) { e_2 = { error: e_2_1 }; }
                    finally {
                        try {
                            if (_d && !_d.done && (_f = _c.return)) _f.call(_c);
                        }
                        finally { if (e_2) throw e_2.error; }
                    }
                }
                return [2 /*return*/, false];
            });
        });
    };
    Object.defineProperty(BoardsServiceProvider.prototype, "boardsConfig", {
        get: function () {
            return this._boardsConfig;
        },
        set: function (config) {
            var _this = this;
            this.doSetBoardsConfig(config);
            this.saveState().finally(function () { return _this.reconcileAvailableBoards().finally(function () { return _this.onBoardsConfigChangedEmitter.fire(_this._boardsConfig); }); });
        },
        enumerable: false,
        configurable: true
    });
    BoardsServiceProvider.prototype.doSetBoardsConfig = function (config) {
        this.logger.info('Board config changed: ', JSON.stringify(config));
        this._boardsConfig = config;
        this.latestBoardsConfig = this._boardsConfig;
        if (this.canUploadTo(this._boardsConfig)) {
            this.latestValidBoardsConfig = this._boardsConfig;
        }
    };
    BoardsServiceProvider.prototype.searchBoards = function (_a) {
        var query = _a.query, cores = _a.cores;
        return __awaiter(this, void 0, void 0, function () {
            var boards, coresFilter, toMatch, compareEntries, normalizedQuery;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.boardsService.allBoards({})];
                    case 1:
                        boards = _b.sent();
                        coresFilter = !!cores && cores.length
                            ? (function (toFilter) { return cores.some(function (core) { return core === toFilter.packageName || core === toFilter.packageId; }); })
                            : function () { return true; };
                        if (!query) {
                            return [2 /*return*/, boards.filter(coresFilter).sort(protocol_1.Board.compare)];
                        }
                        toMatch = (function (toFilter) { return (({ board: toFilter, matches: monaco.filters.matchesFuzzy(query, toFilter.name, true) })); });
                        compareEntries = function (left, right, lookFor) {
                            var leftMatches = left.matches || [];
                            var rightMatches = right.matches || [];
                            if (leftMatches.length && !rightMatches.length) {
                                return -1;
                            }
                            if (!leftMatches.length && rightMatches.length) {
                                return 1;
                            }
                            if (leftMatches.length === 0 && rightMatches.length === 0) {
                                return 0;
                            }
                            var leftLabel = left.board.name.replace(/\r?\n/g, ' ');
                            var rightLabel = right.board.name.replace(/\r?\n/g, ' ');
                            return comparers_1.compareAnything(leftLabel, rightLabel, lookFor);
                        };
                        normalizedQuery = query.toLowerCase();
                        return [2 /*return*/, boards
                                .filter(coresFilter)
                                .map(toMatch)
                                .filter(function (_a) {
                                var matches = _a.matches;
                                return !!matches;
                            })
                                .sort(function (left, right) { return compareEntries(left, right, normalizedQuery); })
                                .map(function (_a) {
                                var board = _a.board;
                                return board;
                            })];
                }
            });
        });
    };
    /**
     * `true` if the `config.selectedBoard` is defined; hence can compile against the board. Otherwise, `false`.
     */
    BoardsServiceProvider.prototype.canVerify = function (config, options) {
        if (config === void 0) { config = this.boardsConfig; }
        if (options === void 0) { options = { silent: true }; }
        if (!config) {
            return false;
        }
        if (!config.selectedBoard) {
            if (!options.silent) {
                this.messageService.warn('No boards selected.', { timeout: 3000 });
            }
            return false;
        }
        return true;
    };
    /**
     * `true` if `canVerify`, the board has an FQBN and the `config.selectedPort` is also set, hence can upload to board. Otherwise, `false`.
     */
    BoardsServiceProvider.prototype.canUploadTo = function (config, options) {
        if (config === void 0) { config = this.boardsConfig; }
        if (options === void 0) { options = { silent: true }; }
        if (!this.canVerify(config, options)) {
            return false;
        }
        var name = config.selectedBoard.name;
        if (!config.selectedPort) {
            if (!options.silent) {
                this.messageService.warn("No ports selected for board: '" + name + "'.", { timeout: 3000 });
            }
            return false;
        }
        if (!config.selectedBoard.fqbn) {
            if (!options.silent) {
                this.messageService.warn("The FQBN is not available for the selected board " + name + ". Do you have the corresponding core installed?", { timeout: 3000 });
            }
            return false;
        }
        return true;
    };
    Object.defineProperty(BoardsServiceProvider.prototype, "availableBoards", {
        get: function () {
            return this._availableBoards;
        },
        enumerable: false,
        configurable: true
    });
    BoardsServiceProvider.prototype.waitUntilAvailable = function (what, timeout) {
        return __awaiter(this, void 0, void 0, function () {
            var find, timeoutTask, waitUntilTask;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        find = function (needle, haystack) {
                            return haystack.find(function (board) { return protocol_1.Board.equals(needle, board) && protocol_1.Port.equals(needle.port, board.port); });
                        };
                        timeoutTask = !!timeout && timeout > 0
                            ? new Promise(function (_, reject) { return setTimeout(function () { return reject(new Error("Timeout after " + timeout + " ms.")); }, timeout); })
                            : new Promise(function () { });
                        waitUntilTask = new Promise(function (resolve) {
                            var candidate = find(what, _this.availableBoards);
                            if (candidate) {
                                resolve();
                                return;
                            }
                            var disposable = _this.onAvailableBoardsChanged(function (availableBoards) {
                                candidate = find(what, availableBoards);
                                if (candidate) {
                                    disposable.dispose();
                                    resolve();
                                }
                            });
                        });
                        return [4 /*yield*/, Promise.race([waitUntilTask, timeoutTask])];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    BoardsServiceProvider.prototype.reconcileAvailableBoards = function () {
        return __awaiter(this, void 0, void 0, function () {
            var attachedBoards, availablePorts, boardsConfig, currentAvailableBoards, availableBoards, availableBoardPorts, attachedSerialBoards, _loop_1, this_1, availableBoardPorts_1, availableBoardPorts_1_1, boardPort, e_3_1, sortedAvailableBoards, hasChanged, i;
            var e_3, _a;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        attachedBoards = this._attachedBoards;
                        availablePorts = this._availablePorts;
                        // Unset the port on the user's config, if it is not available anymore.
                        if (this.boardsConfig.selectedPort && !availablePorts.some(function (port) { return protocol_1.Port.sameAs(port, _this.boardsConfig.selectedPort); })) {
                            this.doSetBoardsConfig({ selectedBoard: this.boardsConfig.selectedBoard, selectedPort: undefined });
                            this.onBoardsConfigChangedEmitter.fire(this._boardsConfig);
                        }
                        boardsConfig = this.boardsConfig;
                        currentAvailableBoards = this._availableBoards;
                        availableBoards = [];
                        availableBoardPorts = availablePorts.filter(protocol_1.Port.isBoardPort);
                        attachedSerialBoards = attachedBoards.filter(function (_a) {
                            var port = _a.port;
                            return !!port;
                        });
                        _loop_1 = function (boardPort) {
                            var state, board, lastSelectedBoard, selected;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        state = AvailableBoard.State.incomplete;
                                        board = attachedSerialBoards.find(function (_a) {
                                            var port = _a.port;
                                            return protocol_1.Port.sameAs(boardPort, port);
                                        });
                                        if (!board) return [3 /*break*/, 1];
                                        state = AvailableBoard.State.recognized;
                                        return [3 /*break*/, 3];
                                    case 1: return [4 /*yield*/, this_1.getLastSelectedBoardOnPort(boardPort)];
                                    case 2:
                                        lastSelectedBoard = _a.sent();
                                        if (lastSelectedBoard) {
                                            board = __assign(__assign({}, lastSelectedBoard), { port: boardPort });
                                            state = AvailableBoard.State.guessed;
                                        }
                                        _a.label = 3;
                                    case 3:
                                        if (!board) {
                                            availableBoards.push({ name: 'Unknown', port: boardPort, state: state });
                                        }
                                        else {
                                            selected = boards_config_1.BoardsConfig.Config.sameAs(boardsConfig, board);
                                            availableBoards.push(__assign(__assign({}, board), { state: state, selected: selected, port: boardPort }));
                                        }
                                        return [2 /*return*/];
                                }
                            });
                        };
                        this_1 = this;
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, 6, 7, 8]);
                        availableBoardPorts_1 = __values(availableBoardPorts), availableBoardPorts_1_1 = availableBoardPorts_1.next();
                        _b.label = 2;
                    case 2:
                        if (!!availableBoardPorts_1_1.done) return [3 /*break*/, 5];
                        boardPort = availableBoardPorts_1_1.value;
                        return [5 /*yield**/, _loop_1(boardPort)];
                    case 3:
                        _b.sent();
                        _b.label = 4;
                    case 4:
                        availableBoardPorts_1_1 = availableBoardPorts_1.next();
                        return [3 /*break*/, 2];
                    case 5: return [3 /*break*/, 8];
                    case 6:
                        e_3_1 = _b.sent();
                        e_3 = { error: e_3_1 };
                        return [3 /*break*/, 8];
                    case 7:
                        try {
                            if (availableBoardPorts_1_1 && !availableBoardPorts_1_1.done && (_a = availableBoardPorts_1.return)) _a.call(availableBoardPorts_1);
                        }
                        finally { if (e_3) throw e_3.error; }
                        return [7 /*endfinally*/];
                    case 8:
                        if (boardsConfig.selectedBoard && !availableBoards.some(function (_a) {
                            var selected = _a.selected;
                            return selected;
                        })) {
                            availableBoards.push(__assign(__assign({}, boardsConfig.selectedBoard), { port: boardsConfig.selectedPort, selected: true, state: AvailableBoard.State.incomplete }));
                        }
                        sortedAvailableBoards = availableBoards.sort(AvailableBoard.compare);
                        hasChanged = sortedAvailableBoards.length !== currentAvailableBoards.length;
                        for (i = 0; !hasChanged && i < sortedAvailableBoards.length; i++) {
                            hasChanged = AvailableBoard.compare(sortedAvailableBoards[i], currentAvailableBoards[i]) !== 0;
                        }
                        if (hasChanged) {
                            this._availableBoards = sortedAvailableBoards;
                            this.onAvailableBoardsChangedEmitter.fire(this._availableBoards);
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    BoardsServiceProvider.prototype.getLastSelectedBoardOnPort = function (port) {
        return __awaiter(this, void 0, void 0, function () {
            var key;
            return __generator(this, function (_a) {
                if (!port) {
                    return [2 /*return*/, undefined];
                }
                key = this.getLastSelectedBoardOnPortKey(port);
                return [2 /*return*/, this.storageService.getData(key)];
            });
        });
    };
    BoardsServiceProvider.prototype.saveState = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, selectedBoard, selectedPort, key;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this.boardsConfig, selectedBoard = _a.selectedBoard, selectedPort = _a.selectedPort;
                        if (!(selectedBoard && selectedPort)) return [3 /*break*/, 2];
                        key = this.getLastSelectedBoardOnPortKey(selectedPort);
                        return [4 /*yield*/, this.storageService.setData(key, selectedBoard)];
                    case 1:
                        _b.sent();
                        _b.label = 2;
                    case 2: return [4 /*yield*/, Promise.all([
                            this.storageService.setData('latest-valid-boards-config', this.latestValidBoardsConfig),
                            this.storageService.setData('latest-boards-config', this.latestBoardsConfig)
                        ])];
                    case 3:
                        _b.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    BoardsServiceProvider.prototype.getLastSelectedBoardOnPortKey = function (port) {
        // TODO: we lose the port's `protocol` info (`serial`, `network`, etc.) here if the `port` is a `string`.
        return "last-selected-board-on-port:" + (typeof port === 'string' ? port : protocol_1.Port.toString(port));
    };
    BoardsServiceProvider.prototype.loadState = function () {
        return __awaiter(this, void 0, void 0, function () {
            var storedLatestValidBoardsConfig, storedLatestBoardsConfig;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.storageService.getData('latest-valid-boards-config')];
                    case 1:
                        storedLatestValidBoardsConfig = _a.sent();
                        if (!storedLatestValidBoardsConfig) return [3 /*break*/, 2];
                        this.latestValidBoardsConfig = storedLatestValidBoardsConfig;
                        if (this.canUploadTo(this.latestValidBoardsConfig)) {
                            this.boardsConfig = this.latestValidBoardsConfig;
                        }
                        return [3 /*break*/, 4];
                    case 2: return [4 /*yield*/, this.storageService.getData('latest-boards-config')];
                    case 3:
                        storedLatestBoardsConfig = _a.sent();
                        if (storedLatestBoardsConfig) {
                            this.latestBoardsConfig = storedLatestBoardsConfig;
                            this.boardsConfig = this.latestBoardsConfig;
                        }
                        _a.label = 4;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    __decorate([
        inversify_1.inject(logger_1.ILogger),
        __metadata("design:type", Object)
    ], BoardsServiceProvider.prototype, "logger", void 0);
    __decorate([
        inversify_1.inject(message_service_1.MessageService),
        __metadata("design:type", message_service_1.MessageService)
    ], BoardsServiceProvider.prototype, "messageService", void 0);
    __decorate([
        inversify_1.inject(storage_service_1.StorageService),
        __metadata("design:type", Object)
    ], BoardsServiceProvider.prototype, "storageService", void 0);
    __decorate([
        inversify_1.inject(protocol_1.BoardsService),
        __metadata("design:type", Object)
    ], BoardsServiceProvider.prototype, "boardsService", void 0);
    __decorate([
        inversify_1.inject(core_1.CommandService),
        __metadata("design:type", Object)
    ], BoardsServiceProvider.prototype, "commandService", void 0);
    __decorate([
        inversify_1.inject(notification_center_1.NotificationCenter),
        __metadata("design:type", notification_center_1.NotificationCenter)
    ], BoardsServiceProvider.prototype, "notificationCenter", void 0);
    BoardsServiceProvider = __decorate([
        inversify_1.injectable()
    ], BoardsServiceProvider);
    return BoardsServiceProvider;
}());
exports.BoardsServiceProvider = BoardsServiceProvider;
var AvailableBoard;
(function (AvailableBoard) {
    var State;
    (function (State) {
        /**
         * Retrieved from the CLI via the `board list` command.
         */
        State[State["recognized"] = 0] = "recognized";
        /**
         * Guessed the name/FQBN of the board from the available board ports (3rd party).
         */
        State[State["guessed"] = 1] = "guessed";
        /**
         * We do not know anything about this board, probably a 3rd party. The user has not selected a board for this port yet.
         */
        State[State["incomplete"] = 2] = "incomplete";
    })(State = AvailableBoard.State || (AvailableBoard.State = {}));
    function is(board) {
        return protocol_1.Board.is(board) && 'state' in board;
    }
    AvailableBoard.is = is;
    function hasPort(board) {
        return !!board.port;
    }
    AvailableBoard.hasPort = hasPort;
    AvailableBoard.compare = function (left, right) {
        if (left.selected && !right.selected) {
            return -1;
        }
        if (right.selected && !left.selected) {
            return 1;
        }
        var result = utils_1.naturalCompare(left.name, right.name);
        if (result !== 0) {
            return result;
        }
        if (left.fqbn && right.fqbn) {
            result = utils_1.naturalCompare(left.fqbn, right.fqbn);
            if (result !== 0) {
                return result;
            }
        }
        if (left.port && right.port) {
            result = protocol_1.Port.compare(left.port, right.port);
            if (result !== 0) {
                return result;
            }
        }
        if (!!left.selected && !right.selected) {
            return -1;
        }
        if (!!right.selected && !left.selected) {
            return 1;
        }
        return left.state - right.state;
    };
})(AvailableBoard = exports.AvailableBoard || (exports.AvailableBoard = {}));
//# sourceMappingURL=boards-service-provider.js.map