"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 __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.");
};
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LibraryServiceImpl = void 0;
var inversify_1 = require("inversify");
var library_service_1 = require("../common/protocol/library-service");
var core_client_provider_1 = require("./core-client-provider");
var lib_pb_1 = require("./cli-protocol/commands/lib_pb");
var installable_1 = require("../common/protocol/installable");
var core_1 = require("@theia/core");
var promise_util_1 = require("@theia/core/lib/common/promise-util");
var node_1 = require("@theia/core/lib/node");
var protocol_1 = require("../common/protocol");
var LibraryServiceImpl = /** @class */ (function () {
    function LibraryServiceImpl() {
        this.ready = new promise_util_1.Deferred();
    }
    LibraryServiceImpl.prototype.init = function () {
        var _this = this;
        this.coreClientProvider.client().then(function (client) {
            if (client) {
                _this.ready.resolve();
            }
            else {
                _this.coreClientProvider.onClientReady(function () { return _this.ready.resolve(); });
            }
        });
    };
    LibraryServiceImpl.prototype.search = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            var coreClient, client, instance, listReq, installedLibsResp, installedLibs, installedLibsIdx, installedLibs_1, installedLibs_1_1, installedLib, lib, req, resp, items;
            var e_1, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.ready.promise];
                    case 1:
                        _b.sent();
                        return [4 /*yield*/, this.coreClientProvider.client()];
                    case 2:
                        coreClient = _b.sent();
                        if (!coreClient) {
                            return [2 /*return*/, []];
                        }
                        client = coreClient.client, instance = coreClient.instance;
                        listReq = new lib_pb_1.LibraryListReq();
                        listReq.setInstance(instance);
                        return [4 /*yield*/, new Promise(function (resolve, reject) { return client.libraryList(listReq, function (err, resp) { return !!err ? reject(err) : resolve(resp); }); })];
                    case 3:
                        installedLibsResp = _b.sent();
                        installedLibs = installedLibsResp.getInstalledLibraryList();
                        installedLibsIdx = new Map();
                        try {
                            for (installedLibs_1 = __values(installedLibs), installedLibs_1_1 = installedLibs_1.next(); !installedLibs_1_1.done; installedLibs_1_1 = installedLibs_1.next()) {
                                installedLib = installedLibs_1_1.value;
                                if (installedLib.hasLibrary()) {
                                    lib = installedLib.getLibrary();
                                    if (lib) {
                                        installedLibsIdx.set(lib.getRealName(), installedLib);
                                    }
                                }
                            }
                        }
                        catch (e_1_1) { e_1 = { error: e_1_1 }; }
                        finally {
                            try {
                                if (installedLibs_1_1 && !installedLibs_1_1.done && (_a = installedLibs_1.return)) _a.call(installedLibs_1);
                            }
                            finally { if (e_1) throw e_1.error; }
                        }
                        req = new lib_pb_1.LibrarySearchReq();
                        req.setQuery(options.query || '');
                        req.setInstance(instance);
                        return [4 /*yield*/, new Promise(function (resolve, reject) { return client.librarySearch(req, function (err, resp) { return !!err ? reject(err) : resolve(resp); }); })];
                    case 4:
                        resp = _b.sent();
                        items = resp.getLibrariesList()
                            .filter(function (item) { return !!item.getLatest(); })
                            .slice(0, 50)
                            .map(function (item) {
                            // TODO: This seems to contain only the latest item instead of all of the items.
                            var availableVersions = item.getReleasesMap().getEntryList().map(function (_a) {
                                var _b = __read(_a, 2), key = _b[0], _ = _b[1];
                                return key;
                            }).sort(installable_1.Installable.Version.COMPARATOR).reverse();
                            var installedVersion;
                            var installed = installedLibsIdx.get(item.getName());
                            if (installed) {
                                installedVersion = installed.getLibrary().getVersion();
                            }
                            return toLibrary({
                                name: item.getName(),
                                installable: true,
                                installedVersion: installedVersion,
                            }, item.getLatest(), availableVersions);
                        });
                        return [2 /*return*/, items];
                }
            });
        });
    };
    LibraryServiceImpl.prototype.list = function (_a) {
        var fqbn = _a.fqbn;
        return __awaiter(this, void 0, void 0, function () {
            var coreClient, client, instance, req, resp;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.ready.promise];
                    case 1:
                        _b.sent();
                        return [4 /*yield*/, this.coreClientProvider.client()];
                    case 2:
                        coreClient = _b.sent();
                        if (!coreClient) {
                            return [2 /*return*/, []];
                        }
                        client = coreClient.client, instance = coreClient.instance;
                        req = new lib_pb_1.LibraryListReq();
                        req.setInstance(instance);
                        req.setAll(true);
                        if (fqbn) {
                            req.setFqbn(fqbn);
                        }
                        return [4 /*yield*/, new Promise(function (resolve, reject) {
                                client.libraryList(req, (function (error, r) {
                                    if (error) {
                                        var message = error.message;
                                        // Required core dependency is missing.
                                        // https://github.com/arduino/arduino-cli/issues/954
                                        if (message.indexOf('missing platform release') !== -1 && message.indexOf('referenced by board') !== -1) {
                                            resolve(undefined);
                                            return;
                                        }
                                        // The core for the board is not installed, `lib list` cannot be filtered based on FQBN.
                                        // https://github.com/arduino/arduino-cli/issues/955
                                        if (message.indexOf('platform') !== -1 && message.indexOf('is not installed') !== -1) {
                                            resolve(undefined);
                                            return;
                                        }
                                        reject(error);
                                        return;
                                    }
                                    resolve(r);
                                }));
                            })];
                    case 3:
                        resp = _b.sent();
                        if (!resp) {
                            return [2 /*return*/, []];
                        }
                        return [2 /*return*/, resp.getInstalledLibraryList().map(function (item) {
                                var library = item.getLibrary();
                                if (!library) {
                                    return undefined;
                                }
                                var installedVersion = library.getVersion();
                                return toLibrary({
                                    name: library.getName(),
                                    label: library.getRealName(),
                                    installedVersion: installedVersion,
                                    installable: true,
                                    description: library.getSentence(),
                                    summary: library.getParagraph(),
                                    moreInfoLink: library.getWebsite(),
                                    includes: library.getProvidesIncludesList(),
                                    location: library.getLocation(),
                                    installDirUri: node_1.FileUri.create(library.getInstallDir()).toString(),
                                    exampleUris: library.getExamplesList().map(function (fsPath) { return node_1.FileUri.create(fsPath).toString(); })
                                }, library, [library.getVersion()]);
                            }).filter(core_1.notEmpty)];
                }
            });
        });
    };
    LibraryServiceImpl.prototype.install = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            var item, version, coreClient, client, instance, req, resp, items, updated;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.ready.promise];
                    case 1:
                        _a.sent();
                        item = options.item;
                        version = !!options.version ? options.version : item.availableVersions[0];
                        return [4 /*yield*/, this.coreClientProvider.client()];
                    case 2:
                        coreClient = _a.sent();
                        if (!coreClient) {
                            return [2 /*return*/];
                        }
                        client = coreClient.client, instance = coreClient.instance;
                        req = new lib_pb_1.LibraryInstallReq();
                        req.setInstance(instance);
                        req.setName(item.name);
                        req.setVersion(version);
                        console.info('>>> Starting library package installation...', item);
                        resp = client.libraryInstall(req);
                        resp.on('data', function (r) {
                            var prog = r.getProgress();
                            if (prog) {
                                _this.outputService.append({ name: 'library', chunk: "downloading " + prog.getFile() + ": " + prog.getCompleted() + "%\n" });
                            }
                        });
                        return [4 /*yield*/, new Promise(function (resolve, reject) {
                                resp.on('end', resolve);
                                resp.on('error', reject);
                            })];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, this.search({})];
                    case 4:
                        items = _a.sent();
                        updated = items.find(function (other) { return library_service_1.LibraryPackage.equals(other, item); }) || item;
                        this.notificationServer.notifyLibraryInstalled({ item: updated });
                        console.info('<<< Library package installation done.', item);
                        return [2 /*return*/];
                }
            });
        });
    };
    LibraryServiceImpl.prototype.uninstall = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            var item, coreClient, client, instance, req, logged, resp;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        item = options.item;
                        return [4 /*yield*/, this.coreClientProvider.client()];
                    case 1:
                        coreClient = _a.sent();
                        if (!coreClient) {
                            return [2 /*return*/];
                        }
                        client = coreClient.client, instance = coreClient.instance;
                        req = new lib_pb_1.LibraryUninstallReq();
                        req.setInstance(instance);
                        req.setName(item.name);
                        req.setVersion(item.installedVersion);
                        console.info('>>> Starting library package uninstallation...', item);
                        logged = false;
                        resp = client.libraryUninstall(req);
                        resp.on('data', function (_) {
                            if (!logged) {
                                _this.outputService.append({ name: 'library', chunk: "uninstalling " + item.name + ":" + item.installedVersion + "%\n" });
                                logged = true;
                            }
                        });
                        return [4 /*yield*/, new Promise(function (resolve, reject) {
                                resp.on('end', resolve);
                                resp.on('error', reject);
                            })];
                    case 2:
                        _a.sent();
                        this.notificationServer.notifyLibraryUninstalled({ item: item });
                        console.info('<<< Library package uninstallation done.', item);
                        return [2 /*return*/];
                }
            });
        });
    };
    LibraryServiceImpl.prototype.dispose = function () {
        this.logger.info('>>> Disposing library service...');
        this.logger.info('<<< Disposed library service.');
    };
    __decorate([
        inversify_1.inject(core_1.ILogger),
        __metadata("design:type", Object)
    ], LibraryServiceImpl.prototype, "logger", void 0);
    __decorate([
        inversify_1.inject(core_client_provider_1.CoreClientProvider),
        __metadata("design:type", core_client_provider_1.CoreClientProvider)
    ], LibraryServiceImpl.prototype, "coreClientProvider", void 0);
    __decorate([
        inversify_1.inject(protocol_1.OutputService),
        __metadata("design:type", Object)
    ], LibraryServiceImpl.prototype, "outputService", void 0);
    __decorate([
        inversify_1.inject(protocol_1.NotificationServiceServer),
        __metadata("design:type", Object)
    ], LibraryServiceImpl.prototype, "notificationServer", void 0);
    __decorate([
        inversify_1.postConstruct(),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], LibraryServiceImpl.prototype, "init", null);
    LibraryServiceImpl = __decorate([
        inversify_1.injectable()
    ], LibraryServiceImpl);
    return LibraryServiceImpl;
}());
exports.LibraryServiceImpl = LibraryServiceImpl;
function toLibrary(pkg, lib, availableVersions) {
    return __assign(__assign({ name: '', label: '', exampleUris: [], installable: false, location: 0 }, pkg), { author: lib.getAuthor(), availableVersions: availableVersions, includes: lib.getProvidesIncludesList(), description: lib.getSentence(), moreInfoLink: lib.getWebsite(), summary: lib.getParagraph() });
}
//# sourceMappingURL=library-service-server-impl.js.map