import * as vscode from 'vscode';
import { FunctionCacheManager, FunctionInfo } from '../functionExtractor';

// 定义跳转提供者类
export class DefinitionProvider implements vscode.DefinitionProvider {
    private cacheManager: FunctionCacheManager;

    constructor(cacheManager: FunctionCacheManager) {
        this.cacheManager = cacheManager;
    }

    // 提供符号定义位置
    async provideDefinition(
        document: vscode.TextDocument,
        position: vscode.Position,
        token: vscode.CancellationToken
    ): Promise<vscode.Definition | vscode.LocationLink[] | undefined> {
        // 检查是否在注释中，如果在注释中则不提供定义跳转
        const line = document.lineAt(position.line);
        const commentIndex = line.text.indexOf('//');
        if (commentIndex >= 0 && position.character > commentIndex) {
            return undefined;
        }

        // 获取光标位置的单词范围
        const range = document.getWordRangeAtPosition(position);
        if (!range) {
            return undefined;
        }

        // 获取单词
        const word = document.getText(range);

        // 查找函数定义
        const functions = this.cacheManager.findFunctionsByName(word);
        if (functions.length > 0) {
            if (functions.length === 1) {
                // 单个函数定义
                const func = functions[0];
                const uri = vscode.Uri.parse(`squirrel:/${func.filePath}`);
                const position = new vscode.Position(func.lineNumber - 1, 0);
                return new vscode.Location(uri, position);
            } else {
                // 多个同名函数定义，返回所有位置
                const locations: vscode.Location[] = [];
                functions.forEach(func => {
                    const uri = vscode.Uri.parse(`squirrel:/${func.filePath}`);
                    const position = new vscode.Position(func.lineNumber - 1, 0);
                    locations.push(new vscode.Location(uri, position));
                });
                return locations;
            }
        }

        return undefined;
    }
}