"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractComponentCommand = void 0;
exports.executeRefactoringCommand = executeRefactoringCommand;
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;
}
async function executeExtractComponentCommand(svelteDoc, refactorArgs) {
    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 = filePath.split('/').pop()?.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() {
        const startPos = (svelteDoc.script || svelteDoc.moduleScript)?.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