import * as vscode from 'vscode';
import { FileEntry, FileModel } from './model';

export class FileProvider implements vscode.TreeDataProvider<FileEntry> {
    private _onDidChangeTreeData = new vscode.EventEmitter<FileEntry | undefined | void>();
    onDidChangeTreeData = this._onDidChangeTreeData.event;

    constructor(private model: FileModel, private output?: vscode.OutputChannel) {}

    refresh(): void {
        this._onDidChangeTreeData.fire();
    }

    getTreeItem(element: FileEntry): vscode.TreeItem {
        const item = new vscode.TreeItem(
            element.name,
            element.isFile ? vscode.TreeItemCollapsibleState.None : vscode.TreeItemCollapsibleState.Collapsed
        );

        // 设置上下文值，用于右键菜单
        item.contextValue = element.isFile ? 'squirrel.file' : 'squirrel.folder';

        // 设置虚拟文件 URI
        const uri = vscode.Uri.parse(`squirrel:/${element.key}`);
        item.resourceUri = uri;

        if (element.isFile) {
            // 设置文件图标
            item.iconPath = new vscode.ThemeIcon('file-code');

            // 为文件设置点击命令
            item.command = {
                command: 'squirrel.openFile',
                title: '打开',
                arguments: [element]
            };

            // 如果有内容，显示状态
            if (element.content) {
                item.description = '已加载';
            } else {
                item.description = '未加载';
            }
        } else {
            // 文件夹图标
            item.iconPath = new vscode.ThemeIcon('folder');
        }

        return item;
    }

    getChildren(element?: FileEntry): Thenable<FileEntry[]> {
        try {
            const result = this.model.getChildren(element?.key);

            if (this.output) {
                const label = element ? `children:${element.key}` : 'children:<root>';
                this.output.appendLine(`[Squirrel] get${label} -> ${result.length} items`);
            }

            return Promise.resolve(result);
        } catch (error) {
            if (this.output) {
                this.output.appendLine(`[Squirrel] Error getting children: ${error}`);
            }
            return Promise.resolve([]);
        }
    }

    getParent?(element: FileEntry): Thenable<FileEntry | undefined> {
        // 简单实现，返回 undefined 表示根目录
        return Promise.resolve(undefined);
    }
}