import { __decorate, __metadata } from "tslib";
import { isFilesystemReady } from '@codeblitzjs/ide-sumi-core';
import { InlineChatHandler } from '@opensumi/ide-ai-native/lib/browser/widget/inline-chat/inline-chat.handler';
import { AppConfig, BrowserModule, ClientAppContribution, EDITOR_COMMANDS, } from '@opensumi/ide-core-browser';
import { CommandContribution, DisposableStore, Domain, Emitter, ILogger, URI, } from '@opensumi/ide-core-common';
import { EditorCollectionService, WorkbenchEditorService } from '@opensumi/ide-editor';
import { Selection, SelectionDirection } from '@opensumi/ide-monaco';
import { InlineChatController } from '@opensumi/ide-ai-native/lib/browser/widget/inline-chat/inline-chat-controller';
import { InlineDiffService } from '@opensumi/ide-ai-native/lib/browser/widget/inline-diff/inline-diff.service';
import { EResultKind } from '@opensumi/ide-ai-native/lib/common';
import { SumiReadableStream } from '@opensumi/ide-utils/lib/stream';
import { requireModule } from '../../api/require';
import { Autowired, Injectable } from '../../modules/opensumi__common-di';
import { MenuContribution } from '../../modules/opensumi__ide-core-browser';
import { ApplyDefaultThemeContribution } from '../theme';
import { IDiffViewerProps } from './common';
import { removeStart } from './utils';
const fse = requireModule('fs-extra');
const path = requireModule('path');
let DiffViewerContribution = class DiffViewerContribution {
    constructor() {
        this._disposables = new DisposableStore();
        this._onPartialEditEvent = this._disposables.add(new Emitter());
        this.onPartialEditEvent = this._onPartialEditEvent.event;
    }
    getFullPath(filePath) {
        return path.join(this.appConfig.workspaceDir, filePath);
    }
    stripDirectory(filePath) {
        const result = removeStart(filePath, this.appConfig.workspaceDir);
        if (result.startsWith('/')) {
            return result.slice(1);
        }
        return result;
    }
    async initialize(app) {
        await isFilesystemReady();
        let previewer;
        this.diffViewerProps.onRef({
            openDiffInTab: async (filePath, oldContent, newContent, options) => {
                const fullPath = this.getFullPath(filePath);
                if (!await fse.pathExists(fullPath)) {
                    await fse.ensureFile(fullPath);
                    await fse.writeFile(fullPath, oldContent);
                }
                const uri = URI.file(fullPath);
                await this.workbenchEditorService.open(uri, Object.assign(Object.assign({}, options), { preview: false }));
                const editor = this.editorCollectionService.getEditorByUri(uri);
                if (previewer) {
                    try {
                        if (previewer) {
                            previewer.handleAction(EResultKind.DISCARD);
                        }
                        previewer.dispose();
                    }
                    catch (error) {
                        this.logger.log(`DiffViewerContribution ~ openDiffInTab: ~ error:`, error);
                    }
                }
                const monacoEditor = editor.monacoEditor;
                monacoEditor.setValue(oldContent);
                const fullRange = monacoEditor.getModel().getFullModelRange();
                const stream = new SumiReadableStream();
                const controller = new InlineChatController();
                controller.mountReadable(stream);
                previewer = this.inlineDiffService.createDiffPreviewer(monacoEditor, {
                    crossSelection: Selection.fromRange(fullRange, SelectionDirection.LTR),
                    chatResponse: controller,
                });
                previewer.addDispose(previewer.onPartialEditEvent((e) => {
                    const fsPath = monacoEditor.getModel().uri.fsPath;
                    this._onPartialEditEvent.fire(Object.assign({ filePath: this.stripDirectory(fsPath) }, e));
                }));
                stream.emitData({
                    kind: 'content',
                    content: newContent,
                });
                stream.end();
            },
            openTab: async (filePath, options) => {
                const fullPath = this.getFullPath(filePath);
                const uri = URI.file(fullPath);
                await this.workbenchEditorService.open(uri, Object.assign({}, options));
            },
            closeTab: async (filePath) => {
                await this.workbenchEditorService.close(URI.file(this.getFullPath(filePath)), false);
            },
            onPartialEditEvent: (cb) => {
                return this.onPartialEditEvent(cb);
            },
            getFileContent: async (filePath) => {
                const fullPath = this.getFullPath(filePath);
                return await fse.readFile(fullPath, 'utf-8');
            },
            acceptAllPartialEdit: async () => {
                if (previewer) {
                    previewer.handleAction(EResultKind.ACCEPT);
                }
            },
            rejectAllPartialEdit: async () => {
                if (previewer) {
                    previewer.handleAction(EResultKind.DISCARD);
                }
            },
        });
    }
    registerCommands() {
    }
    registerMenus(registry) {
        registry.unregisterMenuItem('editor/title', EDITOR_COMMANDS.SPLIT_TO_RIGHT.id);
        registry.unregisterMenuItem('editor/title', EDITOR_COMMANDS.CLOSE_ALL_IN_GROUP.id);
    }
};
__decorate([
    Autowired(IDiffViewerProps),
    __metadata("design:type", Object)
], DiffViewerContribution.prototype, "diffViewerProps", void 0);
__decorate([
    Autowired(WorkbenchEditorService),
    __metadata("design:type", WorkbenchEditorService)
], DiffViewerContribution.prototype, "workbenchEditorService", void 0);
__decorate([
    Autowired(InlineChatHandler),
    __metadata("design:type", InlineChatHandler)
], DiffViewerContribution.prototype, "inlineChatHandler", void 0);
__decorate([
    Autowired(InlineDiffService),
    __metadata("design:type", InlineDiffService)
], DiffViewerContribution.prototype, "inlineDiffService", void 0);
__decorate([
    Autowired(EditorCollectionService),
    __metadata("design:type", EditorCollectionService)
], DiffViewerContribution.prototype, "editorCollectionService", void 0);
__decorate([
    Autowired(AppConfig),
    __metadata("design:type", Object)
], DiffViewerContribution.prototype, "appConfig", void 0);
__decorate([
    Autowired(ILogger),
    __metadata("design:type", Object)
], DiffViewerContribution.prototype, "logger", void 0);
DiffViewerContribution = __decorate([
    Domain(CommandContribution, ClientAppContribution, MenuContribution)
], DiffViewerContribution);
export { DiffViewerContribution };
let DiffViewerModule = class DiffViewerModule extends BrowserModule {
    constructor() {
        super(...arguments);
        this.providers = [
            DiffViewerContribution,
            ApplyDefaultThemeContribution,
        ];
    }
};
DiffViewerModule = __decorate([
    Injectable()
], DiffViewerModule);
export { DiffViewerModule };
//# sourceMappingURL=module.js.map