"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MainThreadWorkspace = void 0;
const tslib_1 = require("tslib");
const di_1 = require("@opensumi/di");
const ide_connection_1 = require("@opensumi/ide-connection");
const ide_core_browser_1 = require("@opensumi/ide-core-browser");
const ide_editor_1 = require("@opensumi/ide-editor");
const ide_extension_storage_1 = require("@opensumi/ide-extension-storage");
const common_1 = require("@opensumi/ide-file-search/lib/common");
const index_1 = require("@opensumi/ide-monaco/lib/browser/monaco-api/index");
const ide_workspace_1 = require("@opensumi/ide-workspace");
const ide_workspace_edit_1 = require("@opensumi/ide-workspace-edit");
const vscode_1 = require("../../../common/vscode");
let MainThreadWorkspace = class MainThreadWorkspace extends ide_core_browser_1.WithEventBus {
    constructor(rpcProtocol) {
        super();
        this.rpcProtocol = rpcProtocol;
        this.proxy = this.rpcProtocol.getProxy(vscode_1.ExtHostAPIIdentifier.ExtHostWorkspace);
        this.processWorkspaceFoldersChanged(this.workspaceService.tryGetRoots());
        this.addDispose((this.workspaceChangeEvent = this.workspaceService.onWorkspaceChanged((roots) => {
            this.processWorkspaceFoldersChanged(roots);
        })));
        this.storageProxy = rpcProtocol.getProxy(vscode_1.ExtHostAPIIdentifier.ExtHostStorage);
    }
    async $startFileSearch(includePattern, options, excludePatternOrDisregardExcludes, maxResult, token) {
        const fileSearchOptions = {
            rootUris: options.cwd ? [options.cwd] : this.workspaceService.tryGetRoots().map((root) => root.uri),
            excludePatterns: excludePatternOrDisregardExcludes ? [excludePatternOrDisregardExcludes] : undefined,
            limit: maxResult,
            includePatterns: [includePattern],
        };
        const result = await this.fileSearchService.find('', fileSearchOptions, token);
        return result;
    }
    isAnyRootChanged(roots) {
        if (!this.roots || this.roots.length !== roots.length) {
            return true;
        }
        return this.roots.some((root, index) => root.uri !== roots[index].uri);
    }
    processWorkspaceFoldersChanged(roots) {
        if (this.isAnyRootChanged(roots) === false) {
            return;
        }
        this.roots = roots;
        this.proxy.$onWorkspaceFoldersChanged({ roots });
        // workspace变化，更新及初始化storage
        this.extensionStorageService.getAll(false).then((v) => {
            this.storageProxy.$updateWorkspaceStorageData(v);
        });
    }
    dispose() {
        super.dispose();
        this.workspaceChangeEvent.dispose();
    }
    async $updateWorkspaceFolders(start, deleteCount, workspaceToName, ...rootsToAdd) {
        await this.workspaceService.spliceRoots(start, deleteCount, workspaceToName, ...rootsToAdd.map((root) => new ide_core_browser_1.URI(root)));
    }
    async $tryApplyWorkspaceEdit(dto, metadata) {
        try {
            const edits = index_1.ResourceEdit.convert(dto);
            const { success } = (await this.bulkEditService.apply(edits, {
                respectAutoSaveConfig: metadata === null || metadata === void 0 ? void 0 : metadata.isRefactoring,
            }));
            return success;
        }
        catch (e) {
            return false;
        }
    }
    async $save(uri) {
        if (!uri) {
            return undefined;
        }
        try {
            const saveUri = ide_core_browser_1.URI.file(uri.path.toString());
            return await this.editorService.save(saveUri);
        }
        catch (error) {
            this.logger.error(`Save Failed: ${error.message}`);
            return undefined;
        }
    }
    async $saveAs(uri) {
        if (!uri) {
            return undefined;
        }
        try {
            return await this.editorService.saveAs(uri);
        }
        catch (error) {
            this.logger.error(`SaveAs Failed: ${error.message}`);
            return undefined;
        }
    }
    async $saveAll() {
        try {
            await this.editorService.saveAll();
            return true;
        }
        catch (e) {
            this.logger.error(e);
            return false;
        }
    }
    onRenameFile(e) {
        this.proxy.$didRenameFile(e.payload.oldUri.codeUri, e.payload.newUri.codeUri);
    }
};
exports.MainThreadWorkspace = MainThreadWorkspace;
tslib_1.__decorate([
    (0, di_1.Autowired)(ide_workspace_1.IWorkspaceService),
    tslib_1.__metadata("design:type", Object)
], MainThreadWorkspace.prototype, "workspaceService", void 0);
tslib_1.__decorate([
    (0, di_1.Autowired)(ide_editor_1.WorkbenchEditorService),
    tslib_1.__metadata("design:type", ide_editor_1.WorkbenchEditorService)
], MainThreadWorkspace.prototype, "editorService", void 0);
tslib_1.__decorate([
    (0, di_1.Autowired)(common_1.FileSearchServicePath),
    tslib_1.__metadata("design:type", Object)
], MainThreadWorkspace.prototype, "fileSearchService", void 0);
tslib_1.__decorate([
    (0, di_1.Autowired)(ide_extension_storage_1.IExtensionStorageService),
    tslib_1.__metadata("design:type", Object)
], MainThreadWorkspace.prototype, "extensionStorageService", void 0);
tslib_1.__decorate([
    (0, di_1.Autowired)(ide_workspace_edit_1.IBulkEditServiceShape),
    tslib_1.__metadata("design:type", Object)
], MainThreadWorkspace.prototype, "bulkEditService", void 0);
tslib_1.__decorate([
    (0, di_1.Autowired)(ide_core_browser_1.ILogger),
    tslib_1.__metadata("design:type", Object)
], MainThreadWorkspace.prototype, "logger", void 0);
tslib_1.__decorate([
    (0, ide_core_browser_1.OnEvent)(ide_workspace_edit_1.WorkspaceEditDidRenameFileEvent),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [ide_workspace_edit_1.WorkspaceEditDidRenameFileEvent]),
    tslib_1.__metadata("design:returntype", void 0)
], MainThreadWorkspace.prototype, "onRenameFile", null);
exports.MainThreadWorkspace = MainThreadWorkspace = tslib_1.__decorate([
    (0, di_1.Injectable)({ multiple: true }),
    tslib_1.__param(0, (0, di_1.Optional)(Symbol())),
    tslib_1.__metadata("design:paramtypes", [Object])
], MainThreadWorkspace);
//# sourceMappingURL=main.thread.workspace.js.map