"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.OnTypeFormattingProvider = void 0;
const vscode = __importStar(require("vscode"));
const beautifyHelper_1 = require("../utils/beautifyHelper");
/**
 * 输入时格式化提供者类 - 使用 js-beautify.js
 */
class OnTypeFormattingProvider {
    /**
     * 在用户输入特定字符时自动格式化代码
     */
    async provideOnTypeFormattingEdits(document, position, ch, options, token) {
        const edits = [];
        try {
            // 检查是否是 Squirrel 代码
            const textBefore = document.getText(new vscode.Range(new vscode.Position(0, 0), position));
            if (!(0, beautifyHelper_1.isSquirrelCode)(textBefore)) {
                return edits;
            }
            // 根据输入的字符执行不同的格式化操作
            switch (ch) {
                case ')':
                    // 输入右括号时格式化当前行
                    edits.push(...this.formatCurrentLine(document, position, options));
                    break;
                case ';':
                    // 输入分号时格式化当前行
                    edits.push(...this.formatCurrentLine(document, position, options));
                    break;
                case '}':
                    // 输入右大括号时格式化整个代码块
                    edits.push(...this.formatCodeBlock(document, position, options));
                    break;
                default:
                    break;
            }
        }
        catch (error) {
            console.error('输入时格式化失败:', error);
        }
        return edits;
    }
    /**
     * 使用 js-beautify 格式化当前行
     */
    formatCurrentLine(document, position, options) {
        const edits = [];
        try {
            // 获取当前行
            const line = document.lineAt(position.line);
            const lineText = line.text;
            // 获取当前行的上下文（向前几行，向后几行）
            const startLine = Math.max(0, position.line - 2);
            const endLine = Math.min(document.lineCount - 1, position.line + 2);
            const contextText = document.getText(new vscode.Range(new vscode.Position(startLine, 0), new vscode.Position(endLine, document.lineAt(endLine).text.length)));
            // 使用 js-beautify 格式化代码块
            const formattedContext = (0, beautifyHelper_1.beautifyCode)(contextText, options);
            // 比较原始文本和格式化后的文本
            if (formattedContext === contextText) {
                return edits; // 没有变化，不需要编辑
            }
            // 应用格式化结果
            const originalLines = contextText.split('\n');
            const formattedLines = formattedContext.split('\n');
            for (let i = 0; i < originalLines.length && i < formattedLines.length; i++) {
                const original = originalLines[i];
                const formatted = formattedLines[i];
                if (original !== formatted) {
                    const lineNumber = startLine + i;
                    const range = new vscode.Range(new vscode.Position(lineNumber, 0), new vscode.Position(lineNumber, document.lineAt(lineNumber).text.length));
                    edits.push(vscode.TextEdit.replace(range, formatted));
                }
            }
        }
        catch (error) {
            console.error('格式化当前行失败:', error);
        }
        return edits;
    }
    /**
     * 使用 js-beautify 格式化代码块
     */
    formatCodeBlock(document, position, options) {
        const edits = [];
        try {
            // 查找匹配的左大括号
            let braceCount = 1;
            let blockStartLine = -1;
            for (let i = position.line - 1; i >= 0; i--) {
                const currentLine = document.lineAt(i);
                const lineText = currentLine.text;
                for (let j = lineText.length - 1; j >= 0; j--) {
                    if (lineText[j] === '}') {
                        braceCount++;
                    }
                    else if (lineText[j] === '{') {
                        braceCount--;
                        if (braceCount === 0) {
                            blockStartLine = i;
                            break;
                        }
                    }
                }
                if (blockStartLine !== -1) {
                    break;
                }
            }
            if (blockStartLine !== -1) {
                // 获取代码块的范围
                const endLine = position.line;
                const blockText = document.getText(new vscode.Range(new vscode.Position(blockStartLine, 0), new vscode.Position(endLine + 1, 0) // 包含右大括号行
                ));
                // 使用 js-beautify 格式化代码块
                const formattedBlock = (0, beautifyHelper_1.beautifyCode)(blockText, options);
                if (formattedBlock === blockText) {
                    return edits; // 没有变化
                }
                // 应用格式化结果
                const range = new vscode.Range(new vscode.Position(blockStartLine, 0), new vscode.Position(endLine + 1, 0));
                edits.push(vscode.TextEdit.replace(range, formattedBlock));
            }
        }
        catch (error) {
            console.error('格式化代码块失败:', error);
        }
        return edits;
    }
}
exports.OnTypeFormattingProvider = OnTypeFormattingProvider;
//# sourceMappingURL=onTypeFormattingProvider.js.map