import { uuidV4 } from "@api-client/core/build/browser.js";
import { FileBindings } from "../base/FileBindings.js";
export class WebFileBindings extends FileBindings {
    constructor() {
        super(...arguments);
        /**
         * Keeps references to file handles mapped to the generated path.
         */
        this.handles = new Map();
    }
    async saveFileDialog(opts = {}) {
        const { excludeAcceptAllOption, filters } = opts;
        const dialogOptions = {
            excludeAcceptAllOption,
        };
        if (Array.isArray(filters) && filters.length) {
            dialogOptions.types = filters;
        }
        try {
            const handle = await window.showSaveFilePicker(dialogOptions);
            const path = uuidV4();
            this.handles.set(path, handle);
            return { canceled: false, filePath: path };
        }
        catch (_) {
            return { canceled: true };
        }
    }
    async openFileDialog(opts = {}) {
        const { excludeAcceptAllOption, filters, multiple } = opts;
        const dialogOptions = {
            excludeAcceptAllOption,
            multiple,
        };
        if (Array.isArray(filters) && filters.length) {
            dialogOptions.types = filters;
        }
        try {
            const handles = await window.showOpenFilePicker(dialogOptions);
            const result = [];
            handles.forEach((handle) => {
                const path = `${uuidV4()}/${handle.name}`;
                result.push(path);
                this.handles.set(path, handle);
            });
            return { canceled: false, filePath: result };
        }
        catch (_) {
            return { canceled: true };
        }
    }
    async writeFile(path, contents, opts = {}) {
        const handle = this.handles.get(path);
        if (!handle) {
            throw new Error(`Invalid file path. The file handle not found.`);
        }
        const stream = await handle.createWritable();
        await stream.write(contents);
        await stream.close();
        if (opts.dispose) {
            this.dispose(path);
        }
    }
    async readFile(path, opts = {}) {
        const handle = this.handles.get(path);
        if (!handle) {
            throw new Error(`Invalid file path. The file handle not found.`);
        }
        const file = await handle.getFile();
        let result;
        if (opts.returnType === 'buffer') {
            result = await file.arrayBuffer();
        }
        else {
            result = await file.text();
        }
        if (opts.dispose) {
            this.dispose(path);
        }
        return result;
    }
    async dispose(path) {
        this.handles.delete(path);
    }
}
//# sourceMappingURL=WebFileBindings.js.map