"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.executeRefactoringCommand = exports.extractComponentCommand = void 0;
const path = __importStar(require("path"));
const vscode_languageserver_1 = require("vscode-languageserver");
const documents_1 = require("../../../../lib/documents");
const utils_1 = require("../../../../utils");
exports.extractComponentCommand = 'extract_to_svelte_component';
async function executeRefactoringCommand(svelteDoc, command, args) {
    if (command === exports.extractComponentCommand && args) {
        return executeExtractComponentCommand(svelteDoc, args[1]);
    }
    return null;
}
exports.executeRefactoringCommand = executeRefactoringCommand;
async function executeExtractComponentCommand(svelteDoc, refactorArgs) {
    var _a;
    const { range } = refactorArgs;
    if (isInvalidSelectionRange()) {
        return 'Invalid selection range';
    }
    let filePath = refactorArgs.filePath || './NewComponent.svelte';
    if (!filePath.endsWith('.svelte')) {
        filePath += '.svelte';
    }
    if (!filePath.startsWith('.')) {
        filePath = './' + filePath;
    }
    const componentName = ((_a = filePath.split('/').pop()) === null || _a === void 0 ? void 0 : _a.split('.svelte')[0]) || '';
    const newFileUri = (0, utils_1.pathToUrl)(path.join(path.dirname(svelteDoc.getFilePath()), filePath));
    return {
        documentChanges: [
            vscode_languageserver_1.TextDocumentEdit.create(vscode_languageserver_1.OptionalVersionedTextDocumentIdentifier.create(svelteDoc.uri, null), [
                vscode_languageserver_1.TextEdit.replace(range, `<${componentName}></${componentName}>`),
                createComponentImportTextEdit()
            ]),
            vscode_languageserver_1.CreateFile.create(newFileUri, { overwrite: true }),
            createNewFileEdit()
        ]
    };
    function isInvalidSelectionRange() {
        const text = svelteDoc.getText();
        const offsetStart = svelteDoc.offsetAt(range.start);
        const offsetEnd = svelteDoc.offsetAt(range.end);
        const validStart = offsetStart === 0 || /[\s\W]/.test(text[offsetStart - 1]);
        const validEnd = offsetEnd === text.length - 1 || /[\s\W]/.test(text[offsetEnd]);
        return (!validStart ||
            !validEnd ||
            (0, documents_1.isRangeInTag)(range, svelteDoc.style) ||
            (0, documents_1.isRangeInTag)(range, svelteDoc.script) ||
            (0, documents_1.isRangeInTag)(range, svelteDoc.moduleScript));
    }
    function createNewFileEdit() {
        const text = svelteDoc.getText();
        const newText = [
            getTemplate(),
            getTag(svelteDoc.script, false),
            getTag(svelteDoc.moduleScript, false),
            getTag(svelteDoc.style, true)
        ]
            .filter((tag) => tag.start >= 0)
            .sort((a, b) => a.start - b.start)
            .map((tag) => tag.text)
            .join('');
        return vscode_languageserver_1.TextDocumentEdit.create(vscode_languageserver_1.OptionalVersionedTextDocumentIdentifier.create(newFileUri, null), [vscode_languageserver_1.TextEdit.insert(vscode_languageserver_1.Position.create(0, 0), newText)]);
        function getTemplate() {
            const startOffset = svelteDoc.offsetAt(range.start);
            return {
                text: text.substring(startOffset, svelteDoc.offsetAt(range.end)) + '\n\n',
                start: startOffset
            };
        }
        function getTag(tag, isStyleTag) {
            if (!tag) {
                return { text: '', start: -1 };
            }
            const tagText = updateRelativeImports(svelteDoc, text.substring(tag.container.start, tag.container.end), filePath, isStyleTag);
            return {
                text: `${tagText}\n\n`,
                start: tag.container.start
            };
        }
    }
    function createComponentImportTextEdit() {
        var _a;
        const startPos = (_a = (svelteDoc.script || svelteDoc.moduleScript)) === null || _a === void 0 ? void 0 : _a.startPos;
        const importText = `\n  import ${componentName} from '${filePath}';\n`;
        return vscode_languageserver_1.TextEdit.insert(startPos || vscode_languageserver_1.Position.create(0, 0), startPos ? importText : `<script>\n${importText}</script>`);
    }
}
// `import {...} from '..'` or `import ... from '..'`
const scriptRelativeImportRegex = /import\s+{[^}]*}.*['"`](((\.\/)|(\.\.\/)).*?)['"`]|import\s+\w+\s+from\s+['"`](((\.\/)|(\.\.\/)).*?)['"`]/g;
// `@import '..'`
const styleRelativeImportRege = /@import\s+['"`](((\.\/)|(\.\.\/)).*?)['"`]/g;
function updateRelativeImports(svelteDoc, tagText, newComponentRelativePath, isStyleTag) {
    const oldPath = path.dirname(svelteDoc.getFilePath());
    const newPath = path.dirname(path.join(oldPath, newComponentRelativePath));
    const regex = isStyleTag ? styleRelativeImportRege : scriptRelativeImportRegex;
    let match = regex.exec(tagText);
    while (match) {
        // match[1]: match before | and style regex. match[5]: match after | (script regex)
        const importPath = match[1] || match[5];
        const newImportPath = (0, documents_1.updateRelativeImport)(oldPath, newPath, importPath);
        tagText = tagText.replace(importPath, newImportPath);
        match = regex.exec(tagText);
    }
    return tagText;
}
//# sourceMappingURL=getRefactorings.js.map