/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
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 __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
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());
    });
};
import { distinct } from '../../../../base/common/arrays.js';
import { CancellationTokenSource } from '../../../../base/common/cancellation.js';
import { createStringDataTransferItem, VSDataTransfer } from '../../../../base/common/dataTransfer.js';
import { Disposable } from '../../../../base/common/lifecycle.js';
import { Mimes } from '../../../../base/common/mime.js';
import { relativePath } from '../../../../base/common/resources.js';
import { URI } from '../../../../base/common/uri.js';
import { toVSDataTransfer } from '../../../browser/dnd.js';
import { registerEditorContribution } from '../../../browser/editorExtensions.js';
import { Range } from '../../../common/core/range.js';
import { ILanguageFeaturesService } from '../../../common/services/languageFeatures.js';
import { performSnippetEdit } from '../../snippet/browser/snippetController2.js';
import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js';
import { extractEditorsDropData } from '../../../../platform/dnd/browser/dnd.js';
import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js';
import { IWorkspaceContextService } from '../../../../platform/workspace/common/workspace.js';
let DropIntoEditorController = class DropIntoEditorController extends Disposable {
    constructor(editor, workspaceContextService, _instantiationService, _languageFeaturesService, _configurationService) {
        super();
        this._instantiationService = _instantiationService;
        this._languageFeaturesService = _languageFeaturesService;
        this._configurationService = _configurationService;
        this._register(editor.onDropIntoEditor(e => this.onDropIntoEditor(editor, e.position, e.event)));
        this._languageFeaturesService.documentOnDropEditProvider.register('*', new DefaultOnDropProvider(workspaceContextService));
        this._register(this._configurationService.onDidChangeConfiguration(e => {
            if (e.affectsConfiguration('workbench.experimental.editor.dropIntoEditor.enabled')) {
                this.updateEditorOptions(editor);
            }
        }));
        this.updateEditorOptions(editor);
    }
    updateEditorOptions(editor) {
        editor.updateOptions({
            enableDropIntoEditor: this._configurationService.getValue('workbench.experimental.editor.dropIntoEditor.enabled')
        });
    }
    onDropIntoEditor(editor, position, dragEvent) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!dragEvent.dataTransfer || !editor.hasModel()) {
                return;
            }
            const model = editor.getModel();
            const modelVersionNow = model.getVersionId();
            const ourDataTransfer = yield this.extractDataTransferData(dragEvent);
            if (ourDataTransfer.size === 0) {
                return;
            }
            if (editor.getModel().getVersionId() !== modelVersionNow) {
                return;
            }
            const cts = new CancellationTokenSource();
            editor.onDidDispose(() => cts.cancel());
            model.onDidChangeContent(() => cts.cancel());
            const providers = this._languageFeaturesService.documentOnDropEditProvider.ordered(model);
            for (const provider of providers) {
                const edit = yield provider.provideDocumentOnDropEdits(model, position, ourDataTransfer, cts.token);
                if (cts.token.isCancellationRequested || editor.getModel().getVersionId() !== modelVersionNow) {
                    return;
                }
                if (edit) {
                    performSnippetEdit(editor, edit);
                    return;
                }
            }
        });
    }
    extractDataTransferData(dragEvent) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!dragEvent.dataTransfer) {
                return new VSDataTransfer();
            }
            const textEditorDataTransfer = toVSDataTransfer(dragEvent.dataTransfer);
            if (!textEditorDataTransfer.has(Mimes.uriList)) {
                const editorData = (yield this._instantiationService.invokeFunction(extractEditorsDropData, dragEvent))
                    .filter(input => input.resource)
                    .map(input => input.resource.toString());
                if (editorData.length) {
                    const str = distinct(editorData).join('\n');
                    textEditorDataTransfer.replace(Mimes.uriList, createStringDataTransferItem(str));
                }
            }
            return textEditorDataTransfer;
        });
    }
};
DropIntoEditorController.ID = 'editor.contrib.dropIntoEditorController';
DropIntoEditorController = __decorate([
    __param(1, IWorkspaceContextService),
    __param(2, IInstantiationService),
    __param(3, ILanguageFeaturesService),
    __param(4, IConfigurationService)
], DropIntoEditorController);
export { DropIntoEditorController };
let DefaultOnDropProvider = class DefaultOnDropProvider {
    constructor(_workspaceContextService) {
        this._workspaceContextService = _workspaceContextService;
    }
    provideDocumentOnDropEdits(model, position, dataTransfer, _token) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const range = new Range(position.lineNumber, position.column, position.lineNumber, position.column);
            const urlListEntry = dataTransfer.get('text/uri-list');
            if (urlListEntry) {
                const urlList = yield urlListEntry.asString();
                return this.doUriListDrop(range, urlList);
            }
            const textEntry = (_a = dataTransfer.get('text')) !== null && _a !== void 0 ? _a : dataTransfer.get(Mimes.text);
            if (textEntry) {
                const text = yield textEntry.asString();
                return { range, snippet: text };
            }
            return undefined;
        });
    }
    doUriListDrop(range, urlList) {
        const uris = [];
        for (const resource of urlList.split('\n')) {
            try {
                uris.push(URI.parse(resource));
            }
            catch (_a) {
                // noop
            }
        }
        if (!uris.length) {
            return;
        }
        const snippet = uris
            .map(uri => {
            const root = this._workspaceContextService.getWorkspaceFolder(uri);
            if (root) {
                const rel = relativePath(root.uri, uri);
                if (rel) {
                    return rel;
                }
            }
            return uri.fsPath;
        })
            .join(' ');
        return { range, snippet };
    }
};
DefaultOnDropProvider = __decorate([
    __param(0, IWorkspaceContextService)
], DefaultOnDropProvider);
registerEditorContribution(DropIntoEditorController.ID, DropIntoEditorController);
