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

export class SquirrelFileSystemProvider implements vscode.FileSystemProvider {
    private model: FileModel;
    private _onDidChangeFile = new vscode.EventEmitter<vscode.FileChangeEvent[]>();
    onDidChangeFile = this._onDidChangeFile.event;
    // 存储文件实例内容，支持多标签页
    private fileContentCache = new Map<string, string>();

    constructor(model: FileModel) {
        this.model = model;
    }

    // 读取文件
    async readFile(uri: vscode.Uri): Promise<Uint8Array> {
        const filePath = this.getPathFromUri(uri);

        // 检查是否有缓存的内容（用于多标签页支持）
        const cacheKey = uri.toString();
        if (this.fileContentCache.has(cacheKey)) {
            const content = this.fileContentCache.get(cacheKey)!;
            return new TextEncoder().encode(content);
        }

        // 从模型获取内容
        const content = await this.model.getFileContent(filePath);

        if (content === undefined) {
            throw vscode.FileSystemError.FileNotFound(uri);
        }

        // 缓存内容以支持多标签页
        this.fileContentCache.set(cacheKey, content);

        return new TextEncoder().encode(content);
    }

    // 写入文件
    async writeFile(uri: vscode.Uri, content: Uint8Array, options: { create: boolean; overwrite: boolean }): Promise<void> {
        const filePath = this.getPathFromUri(uri);
        const textContent = new TextDecoder().decode(content);

        // 更新缓存内容
        const cacheKey = uri.toString();
        this.fileContentCache.set(cacheKey, textContent);

        const success = await this.model.saveFileContent(filePath, textContent);

        if (!success) {
            throw vscode.FileSystemError.Unavailable('保存文件失败');
        }
    }

    // 其他必须实现的方法（简化实现）
    stat(uri: vscode.Uri): vscode.FileStat {
        // 获取文件内容以确定大小
        const cacheKey = uri.toString();
        let content = '';

        if (this.fileContentCache.has(cacheKey)) {
            content = this.fileContentCache.get(cacheKey)!;
        }

        return {
            type: vscode.FileType.File,
            ctime: Date.now(),
            mtime: Date.now(),
            size: Buffer.byteLength(content, 'utf8')
        };
    }

    readDirectory(uri: vscode.Uri): [string, vscode.FileType][] {
        return [];
    }

    createDirectory(uri: vscode.Uri): void {
        throw vscode.FileSystemError.NoPermissions('不支持创建目录');
    }

    delete(uri: vscode.Uri): void {
        throw vscode.FileSystemError.NoPermissions('不支持删除文件');
    }

    rename(oldUri: vscode.Uri, newUri: vscode.Uri, options: { overwrite: boolean }): void {
        throw vscode.FileSystemError.NoPermissions('不支持重命名文件');
    }

    watch(uri: vscode.Uri, options: { recursive: boolean; excludes: string[] }): vscode.Disposable {
        return new vscode.Disposable(() => {});
    }

    // 清理文件缓存
    clearFileCache(uri: vscode.Uri): void {
        const cacheKey = uri.toString();
        this.fileContentCache.delete(cacheKey);
    }

    // 从 URI 解析文件路径
    private getPathFromUri(uri: vscode.Uri): string {
        if (uri.scheme !== 'squirrel') {
            throw vscode.FileSystemError.FileNotFound(uri);
        }
        // 移除查询参数，只返回路径部分
        return uri.path.substring(1); // 去掉开头的 '/'
    }

    // 获取文件实例ID
    private getInstanceId(uri: vscode.Uri): string {
        return uri.query ? new URLSearchParams(uri.query).get('instance') || 'default' : 'default';
    }
}