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;

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

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

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

        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 success = await this.model.saveFileContent(filePath, textContent);

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

    // 其他必须实现的方法（简化实现）
    stat(uri: vscode.Uri): vscode.FileStat {
        return {
            type: vscode.FileType.File,
            ctime: Date.now(),
            mtime: Date.now(),
            size: 0
        };
    }

    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(() => {});
    }

    // 从 URI 解析文件路径
    private getPathFromUri(uri: vscode.Uri): string {
        if (uri.scheme !== 'squirrel') {
            throw vscode.FileSystemError.FileNotFound(uri);
        }
        return uri.path.substring(1); // 去掉开头的 '/'
    }
}