"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileTextChangesToWorkspaceEdit = exports.register = void 0;
const vscode = __importStar(require("vscode-languageserver-protocol"));
const vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
const path_1 = require("path");
const prepareRename_1 = require("./prepareRename");
const getFormatCodeSettings_1 = require("../configs/getFormatCodeSettings");
const getUserPreferences_1 = require("../configs/getUserPreferences");
const shared_1 = require("../shared");
function register(ctx) {
    return async (uri, position, newName) => {
        const document = ctx.getTextDocument(uri);
        if (!document)
            return;
        const fileName = ctx.uriToFileName(document.uri);
        const offset = document.offsetAt(position);
        const renameInfo = (0, shared_1.safeCall)(() => ctx.typescript.languageService.getRenameInfo(fileName, offset, prepareRename_1.renameInfoOptions));
        if (!renameInfo?.canRename)
            return;
        if (renameInfo.fileToRename) {
            const [formatOptions, preferences] = await Promise.all([
                (0, getFormatCodeSettings_1.getFormatCodeSettings)(ctx, document),
                (0, getUserPreferences_1.getUserPreferences)(ctx, document),
            ]);
            return renameFile(renameInfo.fileToRename, newName, formatOptions, preferences);
        }
        const { providePrefixAndSuffixTextForRename } = await (0, getUserPreferences_1.getUserPreferences)(ctx, document);
        const entries = ctx.typescript.languageService.findRenameLocations(fileName, offset, false, false, providePrefixAndSuffixTextForRename);
        if (!entries)
            return;
        const locations = locationsToWorkspaceEdit(newName, entries, ctx);
        return locations;
    };
    function renameFile(fileToRename, newName, formatOptions, preferences) {
        // Make sure we preserve file extension if none provided
        if (!path_1.posix.extname(newName)) {
            newName += path_1.posix.extname(fileToRename);
        }
        const dirname = path_1.posix.dirname(fileToRename);
        const newFilePath = path_1.posix.join(dirname, newName);
        const response = ctx.typescript.languageService.getEditsForFileRename(fileToRename, newFilePath, formatOptions, preferences);
        const edits = fileTextChangesToWorkspaceEdit(response, ctx);
        if (!edits.documentChanges) {
            edits.documentChanges = [];
        }
        edits.documentChanges.push(vscode.RenameFile.create(ctx.fileNameToUri(fileToRename), ctx.fileNameToUri(newFilePath)));
        return edits;
    }
}
exports.register = register;
function fileTextChangesToWorkspaceEdit(changes, ctx) {
    const workspaceEdit = {};
    for (const change of changes) {
        if (!workspaceEdit.documentChanges) {
            workspaceEdit.documentChanges = [];
        }
        const uri = ctx.fileNameToUri(change.fileName);
        let doc = ctx.getTextDocument(uri);
        if (change.isNewFile) {
            workspaceEdit.documentChanges.push(vscode.CreateFile.create(uri));
            doc = vscode_languageserver_textdocument_1.TextDocument.create(uri, 'typescript', 0, '');
        }
        if (!doc)
            continue;
        const docEdit = vscode.TextDocumentEdit.create({
            uri,
            version: null, // fix https://github.com/johnsoncodehk/volar/issues/2025
        }, []);
        for (const textChange of change.textChanges) {
            docEdit.edits.push({
                newText: textChange.newText,
                range: {
                    start: doc.positionAt(textChange.span.start),
                    end: doc.positionAt(textChange.span.start + textChange.span.length),
                },
            });
        }
        workspaceEdit.documentChanges.push(docEdit);
    }
    return workspaceEdit;
}
exports.fileTextChangesToWorkspaceEdit = fileTextChangesToWorkspaceEdit;
function locationsToWorkspaceEdit(newText, locations, ctx) {
    const workspaceEdit = {};
    for (const location of locations) {
        if (!workspaceEdit.changes) {
            workspaceEdit.changes = {};
        }
        const uri = ctx.fileNameToUri(location.fileName);
        const doc = ctx.getTextDocument(uri);
        if (!doc)
            continue;
        if (!workspaceEdit.changes[uri]) {
            workspaceEdit.changes[uri] = [];
        }
        let _newText = newText;
        if (location.prefixText)
            _newText = location.prefixText + _newText;
        if (location.suffixText)
            _newText = _newText + location.suffixText;
        workspaceEdit.changes[uri].push({
            newText: _newText,
            range: {
                start: doc.positionAt(location.textSpan.start),
                end: doc.positionAt(location.textSpan.start + location.textSpan.length),
            },
        });
    }
    return workspaceEdit;
}
//# sourceMappingURL=rename.js.map