"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 };
    }
};
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.SketchesServiceClientImpl = void 0;
var inversify_1 = require("inversify");
var uri_1 = require("@theia/core/lib/common/uri");
var objects_1 = require("@theia/core/lib/common/objects");
var file_service_1 = require("@theia/filesystem/lib/browser/file-service");
var message_service_1 = require("@theia/core/lib/common/message-service");
var workspace_service_1 = require("@theia/workspace/lib/browser/workspace-service");
var protocol_1 = require("../../common/protocol");
var config_service_1 = require("./config-service");
var core_1 = require("@theia/core");
var SketchesServiceClientImpl = /** @class */ (function () {
    function SketchesServiceClientImpl() {
        this.toDispose = new core_1.DisposableCollection();
        this.sketches = new Map();
        this.sketchbookDidChangeEmitter = new core_1.Emitter();
        this.onSketchbookDidChange = this.sketchbookDidChangeEmitter.event;
        this.bufferedSketchbookEvents = [];
    }
    SketchesServiceClientImpl.prototype.onStart = function () {
        var _this = this;
        this.configService.getConfiguration().then(function (_a) {
            var sketchDirUri = _a.sketchDirUri;
            _this.sketchService.getSketches(sketchDirUri).then(function (sketches) {
                var e_1, _a;
                var sketchbookUri = new uri_1.default(sketchDirUri);
                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;
                        _this.sketches.set(sketch.uri, 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; }
                }
                _this.toDispose.push(_this.fileService.watch(new uri_1.default(sketchDirUri), { recursive: true, excludes: [] }));
                _this.toDispose.push(_this.fileService.onDidFilesChange(function (event) { return __awaiter(_this, void 0, void 0, function () {
                    var _a, _b, _c, type, resource, toAdd, _d, uri, toDelete, e_2_1;
                    var e_2, _e;
                    return __generator(this, function (_f) {
                        switch (_f.label) {
                            case 0:
                                _f.trys.push([0, 9, 10, 11]);
                                _a = __values(event.changes), _b = _a.next();
                                _f.label = 1;
                            case 1:
                                if (!!_b.done) return [3 /*break*/, 8];
                                _c = _b.value, type = _c.type, resource = _c.resource;
                                if (!sketchbookUri.isEqualOrParent(resource)) return [3 /*break*/, 7];
                                if (!protocol_1.Sketch.isSketchFile(resource)) return [3 /*break*/, 7];
                                if (!(type === 1 /* ADDED */)) return [3 /*break*/, 6];
                                _f.label = 2;
                            case 2:
                                _f.trys.push([2, 4, , 5]);
                                return [4 /*yield*/, this.sketchService.loadSketch(resource.parent.toString())];
                            case 3:
                                toAdd = _f.sent();
                                if (!this.sketches.has(toAdd.uri)) {
                                    console.log("New sketch '" + toAdd.name + "' was crated in sketchbook '" + sketchDirUri + "'.");
                                    this.sketches.set(toAdd.uri, toAdd);
                                    this.fireSoon(toAdd, 'created');
                                }
                                return [3 /*break*/, 5];
                            case 4:
                                _d = _f.sent();
                                return [3 /*break*/, 5];
                            case 5: return [3 /*break*/, 7];
                            case 6:
                                if (type === 2 /* DELETED */) {
                                    uri = resource.parent.toString();
                                    toDelete = this.sketches.get(uri);
                                    if (toDelete) {
                                        console.log("Sketch '" + toDelete.name + "' was removed from sketchbook '" + sketchbookUri + "'.");
                                        this.sketches.delete(uri);
                                        this.fireSoon(toDelete, 'removed');
                                    }
                                }
                                _f.label = 7;
                            case 7:
                                _b = _a.next();
                                return [3 /*break*/, 1];
                            case 8: return [3 /*break*/, 11];
                            case 9:
                                e_2_1 = _f.sent();
                                e_2 = { error: e_2_1 };
                                return [3 /*break*/, 11];
                            case 10:
                                try {
                                    if (_b && !_b.done && (_e = _a.return)) _e.call(_a);
                                }
                                finally { if (e_2) throw e_2.error; }
                                return [7 /*endfinally*/];
                            case 11: return [2 /*return*/];
                        }
                    });
                }); }));
            });
        });
    };
    SketchesServiceClientImpl.prototype.onStop = function () {
        this.toDispose.dispose();
    };
    SketchesServiceClientImpl.prototype.currentSketch = function () {
        return __awaiter(this, void 0, void 0, function () {
            var sketches;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, Promise.all(this.workspaceService.tryGetRoots().map(function (_a) {
                            var resource = _a.resource;
                            return _this.sketchService.getSketchFolder(resource.toString());
                        }))];
                    case 1:
                        sketches = (_a.sent()).filter(objects_1.notEmpty);
                        if (!sketches.length) {
                            return [2 /*return*/, undefined];
                        }
                        if (sketches.length > 1) {
                            console.log("Multiple sketch folders were found in the workspace. Falling back to the first one. Sketch folders: " + JSON.stringify(sketches));
                        }
                        return [2 /*return*/, sketches[0]];
                }
            });
        });
    };
    SketchesServiceClientImpl.prototype.currentSketchFile = function () {
        return __awaiter(this, void 0, void 0, function () {
            var sketch, uri, exists;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.currentSketch()];
                    case 1:
                        sketch = _a.sent();
                        if (!sketch) return [3 /*break*/, 3];
                        uri = sketch.mainFileUri;
                        return [4 /*yield*/, this.fileService.exists(new uri_1.default(uri))];
                    case 2:
                        exists = _a.sent();
                        if (!exists) {
                            this.messageService.warn("Could not find sketch file: " + uri);
                            return [2 /*return*/, undefined];
                        }
                        return [2 /*return*/, uri];
                    case 3: return [2 /*return*/, undefined];
                }
            });
        });
    };
    SketchesServiceClientImpl.prototype.fireSoon = function (sketch, type) {
        var _this = this;
        this.bufferedSketchbookEvents.push({ type: type, sketch: sketch });
        if (typeof this.fireSoonHandle === 'number') {
            window.clearTimeout(this.fireSoonHandle);
        }
        this.fireSoonHandle = window.setTimeout(function () {
            var e_3, _a;
            var event = {
                created: [],
                removed: []
            };
            try {
                for (var _b = __values(_this.bufferedSketchbookEvents), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var _d = _c.value, type_1 = _d.type, sketch_1 = _d.sketch;
                    if (type_1 === 'created') {
                        event.created.push(sketch_1);
                    }
                    else {
                        event.removed.push(sketch_1);
                    }
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_3) throw e_3.error; }
            }
            _this.sketchbookDidChangeEmitter.fire(event);
            _this.bufferedSketchbookEvents.length = 0;
        }, 100);
    };
    __decorate([
        inversify_1.inject(file_service_1.FileService),
        __metadata("design:type", file_service_1.FileService)
    ], SketchesServiceClientImpl.prototype, "fileService", void 0);
    __decorate([
        inversify_1.inject(message_service_1.MessageService),
        __metadata("design:type", message_service_1.MessageService)
    ], SketchesServiceClientImpl.prototype, "messageService", void 0);
    __decorate([
        inversify_1.inject(protocol_1.SketchesService),
        __metadata("design:type", Object)
    ], SketchesServiceClientImpl.prototype, "sketchService", void 0);
    __decorate([
        inversify_1.inject(workspace_service_1.WorkspaceService),
        __metadata("design:type", workspace_service_1.WorkspaceService)
    ], SketchesServiceClientImpl.prototype, "workspaceService", void 0);
    __decorate([
        inversify_1.inject(config_service_1.ConfigService),
        __metadata("design:type", Object)
    ], SketchesServiceClientImpl.prototype, "configService", void 0);
    SketchesServiceClientImpl = __decorate([
        inversify_1.injectable()
    ], SketchesServiceClientImpl);
    return SketchesServiceClientImpl;
}());
exports.SketchesServiceClientImpl = SketchesServiceClientImpl;
//# sourceMappingURL=sketches-service-client-impl.js.map