import * as vscode from 'vscode';
import { beautifyCode, isSquirrelCode } from '../utils/beautifyHelper';

/**
 * 输入时格式化提供者类 - 使用 js-beautify.js
 */
export class OnTypeFormattingProvider implements vscode.OnTypeFormattingEditProvider {
    /**
     * 在用户输入特定字符时自动格式化代码
     */
    async provideOnTypeFormattingEdits(
        document: vscode.TextDocument,
        position: vscode.Position,
        ch: string,
        options: vscode.FormattingOptions,
        token: vscode.CancellationToken
    ): Promise<vscode.TextEdit[]> {
        const edits: vscode.TextEdit[] = [];

        try {
            // 检查是否是 Squirrel 代码
            const textBefore = document.getText(new vscode.Range(new vscode.Position(0, 0), position));
            if (!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 格式化当前行
     */
    private formatCurrentLine(
        document: vscode.TextDocument,
        position: vscode.Position,
        options: vscode.FormattingOptions
    ): vscode.TextEdit[] {
        const edits: vscode.TextEdit[] = [];

        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 = 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 格式化代码块
     */
    private formatCodeBlock(
        document: vscode.TextDocument,
        position: vscode.Position,
        options: vscode.FormattingOptions
    ): vscode.TextEdit[] {
        const edits: vscode.TextEdit[] = [];

        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 = 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;
    }
}