import * as vscode from 'vscode';
import { FileModel } from './model';
import { FileProvider } from './provider';
import { SquirrelFileSystemProvider } from './fileSystemProvider';
import { registerCommands } from './commands';
import { FunctionExtractor } from './functionExtractor';
import { CompletionProvider, DotCompletionProvider } from './providers/completionProvider';
import { HoverProvider } from './providers/hoverProvider';
import { DefinitionProvider } from './providers/definitionProvider';
import { SignatureHelpProvider } from './providers/signatureHelpProvider';
import { OnTypeFormattingProvider } from './providers/onTypeFormattingProvider';
import { DocumentFormattingProvider } from './providers/documentFormattingProvider';
import { CodeErrorProvider } from './providers/codeErrorProvider';
import { ApiParser } from './providers/apiParser';
import { sendFileToCppService, checkCppServiceConnection } from './localClient';

export function activate(context: vscode.ExtensionContext) {
    console.log('Squirrel NUT Explorer 正在激活...');

    // 初始化API解析器
    const apiParser = ApiParser.getInstance();

    // 创建模型和提供者
    const model = new FileModel();
    const provider = new FileProvider(model);
    const functionExtractor = new FunctionExtractor();
    const output = vscode.window.createOutputChannel('Squirrel');

    // 创建自动完成提供者
    const completionProvider = new CompletionProvider(functionExtractor.getCacheManager());
    const dotCompletionProvider = new DotCompletionProvider();

    // 创建悬停信息提供者
    const hoverProvider = new HoverProvider(functionExtractor.getCacheManager());

    // 创建定义跳转提供者
    const definitionProvider = new DefinitionProvider(functionExtractor.getCacheManager());

    // 创建签名帮助提供者
    const signatureHelpProvider = new SignatureHelpProvider(functionExtractor.getCacheManager());

    // 创建输入时格式化提供者
    const onTypeFormattingProvider = new OnTypeFormattingProvider();

    // 创建文档格式化提供者
    const documentFormattingProvider = new DocumentFormattingProvider();

    // 创建代码错误检测提供者
    const codeErrorProvider = new CodeErrorProvider();
    const diagnosticCollection = vscode.languages.createDiagnosticCollection('squirrel');

    // 注册树形数据提供者
    vscode.window.registerTreeDataProvider('squirrelExplorerView', provider);

    // 注册自动完成提供者
    context.subscriptions.push(
        vscode.languages.registerCompletionItemProvider('squirrel', completionProvider, ''),
        vscode.languages.registerCompletionItemProvider('squirrel', dotCompletionProvider, '.')
    );

    // 注册悬停信息提供者
    context.subscriptions.push(
        vscode.languages.registerHoverProvider('squirrel', hoverProvider)
    );

    // 注册定义跳转提供者
    context.subscriptions.push(
        vscode.languages.registerDefinitionProvider('squirrel', definitionProvider)
    );

    // 注册签名帮助提供者
    context.subscriptions.push(
        vscode.languages.registerSignatureHelpProvider('squirrel', signatureHelpProvider, '(', ',')
    );

    // 注册输入时格式化提供者
    context.subscriptions.push(
        vscode.languages.registerOnTypeFormattingEditProvider('squirrel', onTypeFormattingProvider, ')', ';', '}')
    );

    // 注册文档格式化提供者
    context.subscriptions.push(
        vscode.languages.registerDocumentFormattingEditProvider('squirrel', documentFormattingProvider)
    );

    // 注册代码错误检测提供者
    context.subscriptions.push(
        vscode.languages.registerCodeActionsProvider('squirrel', codeErrorProvider),
        diagnosticCollection
    );

    // 注册文档诊断监听器
    context.subscriptions.push(
        vscode.workspace.onDidChangeTextDocument(event => {
            if (event.document.languageId === 'squirrel') {
                CodeErrorProvider.provideDiagnostics(event.document, diagnosticCollection);
            }
        }),
        vscode.window.onDidChangeActiveTextEditor(editor => {
            if (editor && editor.document.languageId === 'squirrel') {
                CodeErrorProvider.provideDiagnostics(editor.document, diagnosticCollection);
            }
        }),
        vscode.workspace.onDidOpenTextDocument(document => {
            if (document.languageId === 'squirrel') {
                CodeErrorProvider.provideDiagnostics(document, diagnosticCollection);
            }
        })
    );

    // 对所有已打开的squirrel文档进行初始诊断
    vscode.workspace.textDocuments.forEach(document => {
        if (document.languageId === 'squirrel') {
            CodeErrorProvider.provideDiagnostics(document, diagnosticCollection);
        }
    });

    // 注册文件系统提供者
    const fileSystemProvider = new SquirrelFileSystemProvider(model);
    vscode.workspace.registerFileSystemProvider('squirrel', fileSystemProvider, {
        isCaseSensitive: true
    });

    // 将 fileSystemProvider 添加到 context 以便在 commands 中使用
    (global as any).fileSystemProvider = fileSystemProvider;

    // 注册所有命令
    console.log('正在注册命令...');
    registerCommands(context, model, provider, functionExtractor, output);
    console.log('命令注册完成');

    // 注册工作区配置变更监听
    const configChangeListener = vscode.workspace.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration('squirrel')) {
            model.updateConfig();
            output.appendLine('[Squirrel] 配置已更新');
        }
    });

    // 注册文件保存事件
    const saveListener = vscode.workspace.onDidSaveTextDocument(async (doc) => {
        if (doc.uri.scheme === 'squirrel') {
            const filePath = doc.uri.path.substring(1); // 去掉开头的 '/'

            // 当文件保存成功后执行UI更新和缓存更新
            output.appendLine(`[Squirrel] 文件 ${filePath} 已保存到服务器`);
            provider.refresh();

            // 更新函数缓存
            await functionExtractor.updateFileCache(model, filePath);
        }
    });

    // 注册文件关闭事件以清理缓存
    const closeListener = vscode.workspace.onDidCloseTextDocument((doc) => {
        if (doc.uri.scheme === 'squirrel') {
            fileSystemProvider.clearFileCache(doc.uri);
        }
    });

    context.subscriptions.push(configChangeListener, saveListener, closeListener);

    output.appendLine('[Squirrel] 扩展激活完成');
    output.show();

    // 显示欢迎信息
    vscode.window.showInformationMessage('Squirrel NUT Explorer 已激活，请点击"连接到 pvfUtility API"开始使用');
}

export function deactivate() {
    console.log('Squirrel NUT Explorer 正在停用...');
}