"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CoreServiceImpl = void 0;
var file_uri_1 = require("@theia/core/lib/node/file-uri");
var inversify_1 = require("inversify");
var path_1 = require("path");
var compile_pb_1 = require("./cli-protocol/commands/compile_pb");
var core_client_provider_1 = require("./core-client-provider");
var upload_pb_1 = require("./cli-protocol/commands/upload_pb");
var output_service_1 = require("../common/protocol/output-service");
var protocol_1 = require("../common/protocol");
var utils_1 = require("../common/utils");
var CoreServiceImpl = /** @class */ (function () {
    function CoreServiceImpl() {
    }
    CoreServiceImpl.prototype.compile = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            var sketchUri, fqbn, sketchFilePath, sketchpath, coreClient, client, instance, compilerReq, result, e_1;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.outputService.append({ name: 'compile', chunk: 'Compile...\n' + JSON.stringify(options, null, 2) + '\n--------------------------\n' });
                        sketchUri = options.sketchUri, fqbn = options.fqbn;
                        sketchFilePath = file_uri_1.FileUri.fsPath(sketchUri);
                        sketchpath = path_1.dirname(sketchFilePath);
                        return [4 /*yield*/, this.coreClient()];
                    case 1:
                        coreClient = _a.sent();
                        client = coreClient.client, instance = coreClient.instance;
                        compilerReq = new compile_pb_1.CompileReq();
                        compilerReq.setInstance(instance);
                        compilerReq.setSketchpath(sketchpath);
                        if (fqbn) {
                            compilerReq.setFqbn(fqbn);
                        }
                        compilerReq.setOptimizefordebug(options.optimizeForDebug);
                        compilerReq.setPreprocess(false);
                        compilerReq.setVerbose(options.verbose);
                        compilerReq.setQuiet(false);
                        compilerReq.setExportBinaries(options.exportBinaries);
                        result = client.compile(compilerReq);
                        _a.label = 2;
                    case 2:
                        _a.trys.push([2, 4, , 5]);
                        return [4 /*yield*/, new Promise(function (resolve, reject) {
                                result.on('data', function (cr) {
                                    _this.outputService.append({ name: 'compile', chunk: Buffer.from(cr.getOutStream_asU8()).toString() });
                                    _this.outputService.append({ name: 'compile', chunk: Buffer.from(cr.getErrStream_asU8()).toString() });
                                });
                                result.on('error', function (error) { return reject(error); });
                                result.on('end', function () { return resolve(); });
                            })];
                    case 3:
                        _a.sent();
                        this.outputService.append({ name: 'compile', chunk: '\n--------------------------\nCompilation complete.\n' });
                        return [3 /*break*/, 5];
                    case 4:
                        e_1 = _a.sent();
                        this.outputService.append({ name: 'compile', chunk: "Compilation error: " + e_1 + "\n", severity: 'error' });
                        throw e_1;
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    CoreServiceImpl.prototype.upload = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.doUpload(options, function () { return new upload_pb_1.UploadReq(); }, function (client, req) { return client.upload(req); })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    CoreServiceImpl.prototype.uploadUsingProgrammer = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.doUpload(options, function () { return new upload_pb_1.UploadUsingProgrammerReq(); }, function (client, req) { return client.uploadUsingProgrammer(req); }, 'upload using programmer')];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    CoreServiceImpl.prototype.doUpload = function (options, requestProvider, responseHandler, task) {
        if (task === void 0) { task = 'upload'; }
        return __awaiter(this, void 0, void 0, function () {
            var chunk, sketchUri, fqbn, port, programmer, sketchFilePath, sketchpath, coreClient, client, instance, req, result, e_2;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.compile(Object.assign(options, { exportBinaries: false }))];
                    case 1:
                        _a.sent();
                        chunk = utils_1.firstToUpperCase(task) + '...\n';
                        this.outputService.append({ name: 'upload', chunk: chunk + JSON.stringify(options, null, 2) + '\n--------------------------\n' });
                        sketchUri = options.sketchUri, fqbn = options.fqbn, port = options.port, programmer = options.programmer;
                        sketchFilePath = file_uri_1.FileUri.fsPath(sketchUri);
                        sketchpath = path_1.dirname(sketchFilePath);
                        return [4 /*yield*/, this.coreClient()];
                    case 2:
                        coreClient = _a.sent();
                        client = coreClient.client, instance = coreClient.instance;
                        req = requestProvider();
                        req.setInstance(instance);
                        req.setSketchPath(sketchpath);
                        if (fqbn) {
                            req.setFqbn(fqbn);
                        }
                        if (port) {
                            req.setPort(port);
                        }
                        if (programmer) {
                            req.setProgrammer(programmer.id);
                        }
                        req.setVerbose(options.verbose);
                        req.setVerify(options.verify);
                        result = responseHandler(client, req);
                        _a.label = 3;
                    case 3:
                        _a.trys.push([3, 5, , 6]);
                        return [4 /*yield*/, new Promise(function (resolve, reject) {
                                result.on('data', function (resp) {
                                    _this.outputService.append({ name: task, chunk: Buffer.from(resp.getOutStream_asU8()).toString() });
                                    _this.outputService.append({ name: task, chunk: Buffer.from(resp.getErrStream_asU8()).toString() });
                                });
                                result.on('error', function (error) { return reject(error); });
                                result.on('end', function () { return resolve(); });
                            })];
                    case 4:
                        _a.sent();
                        this.outputService.append({ name: 'upload', chunk: '\n--------------------------\n' + utils_1.firstToLowerCase(task) + ' complete.\n' });
                        return [3 /*break*/, 6];
                    case 5:
                        e_2 = _a.sent();
                        this.outputService.append({ name: 'upload', chunk: utils_1.firstToUpperCase(task) + " error: " + e_2 + "\n", severity: 'error' });
                        throw e_2;
                    case 6: return [2 /*return*/];
                }
            });
        });
    };
    CoreServiceImpl.prototype.burnBootloader = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            var coreClient, client, instance, fqbn, port, programmer, burnReq, result, e_3;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.coreClient()];
                    case 1:
                        coreClient = _a.sent();
                        client = coreClient.client, instance = coreClient.instance;
                        fqbn = options.fqbn, port = options.port, programmer = options.programmer;
                        burnReq = new upload_pb_1.BurnBootloaderReq();
                        burnReq.setInstance(instance);
                        if (fqbn) {
                            burnReq.setFqbn(fqbn);
                        }
                        if (port) {
                            burnReq.setPort(port);
                        }
                        if (programmer) {
                            burnReq.setProgrammer(programmer.id);
                        }
                        burnReq.setVerify(options.verify);
                        burnReq.setVerbose(options.verbose);
                        result = client.burnBootloader(burnReq);
                        _a.label = 2;
                    case 2:
                        _a.trys.push([2, 4, , 5]);
                        return [4 /*yield*/, new Promise(function (resolve, reject) {
                                result.on('data', function (resp) {
                                    _this.outputService.append({ name: 'bootloader', chunk: Buffer.from(resp.getOutStream_asU8()).toString() });
                                    _this.outputService.append({ name: 'bootloader', chunk: Buffer.from(resp.getErrStream_asU8()).toString() });
                                });
                                result.on('error', function (error) { return reject(error); });
                                result.on('end', function () { return resolve(); });
                            })];
                    case 3:
                        _a.sent();
                        return [3 /*break*/, 5];
                    case 4:
                        e_3 = _a.sent();
                        this.outputService.append({ name: 'bootloader', chunk: "Error while burning the bootloader: " + e_3 + "\n", severity: 'error' });
                        throw e_3;
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    CoreServiceImpl.prototype.coreClient = function () {
        return __awaiter(this, void 0, void 0, function () {
            var coreClient;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new Promise(function (resolve) { return __awaiter(_this, void 0, void 0, function () {
                            var client, toDispose;
                            var _this = this;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, this.coreClientProvider.client()];
                                    case 1:
                                        client = _a.sent();
                                        if (client) {
                                            resolve(client);
                                            return [2 /*return*/];
                                        }
                                        toDispose = this.coreClientProvider.onClientReady(function () { return __awaiter(_this, void 0, void 0, function () {
                                            var client;
                                            return __generator(this, function (_a) {
                                                switch (_a.label) {
                                                    case 0: return [4 /*yield*/, this.coreClientProvider.client()];
                                                    case 1:
                                                        client = _a.sent();
                                                        if (client) {
                                                            toDispose.dispose();
                                                            resolve(client);
                                                            return [2 /*return*/];
                                                        }
                                                        return [2 /*return*/];
                                                }
                                            });
                                        }); });
                                        return [2 /*return*/];
                                }
                            });
                        }); })];
                    case 1:
                        coreClient = _a.sent();
                        return [2 /*return*/, coreClient];
                }
            });
        });
    };
    __decorate([
        inversify_1.inject(core_client_provider_1.CoreClientProvider),
        __metadata("design:type", core_client_provider_1.CoreClientProvider)
    ], CoreServiceImpl.prototype, "coreClientProvider", void 0);
    __decorate([
        inversify_1.inject(output_service_1.OutputService),
        __metadata("design:type", Object)
    ], CoreServiceImpl.prototype, "outputService", void 0);
    __decorate([
        inversify_1.inject(protocol_1.NotificationServiceServer),
        __metadata("design:type", Object)
    ], CoreServiceImpl.prototype, "notificationService", void 0);
    CoreServiceImpl = __decorate([
        inversify_1.injectable()
    ], CoreServiceImpl);
    return CoreServiceImpl;
}());
exports.CoreServiceImpl = CoreServiceImpl;
//# sourceMappingURL=core-service-impl.js.map