import type { FileReadOptions, FileWriteOptions, IOpenFileDialogInit, IOpenFileDialogResult, ISaveFileDialogInit, ISaveFileDialogResult } from "../bindings/base/FileBindings.js";
import { EventTypes } from "./EventTypes.js";

export const FilesystemEvents = Object.freeze({
  requestSaveFile: async (opts?: ISaveFileDialogInit, target: EventTarget = document.body): Promise<ISaveFileDialogResult | undefined> => {
    const e = new CustomEvent(EventTypes.Filesystem.requestSaveFile, {
      bubbles: true,
      composed: true,
      cancelable: true,
      detail: {
        options: opts,
        result: undefined,
      }
    });
    target.dispatchEvent(e);
    return ((e.detail.result as unknown) as Promise<ISaveFileDialogResult>);
  },

  requestOpenFile: async (opts?: IOpenFileDialogInit, target: EventTarget = document.body): Promise<IOpenFileDialogResult | undefined> => {
    const e = new CustomEvent(EventTypes.Filesystem.requestOpenFile, {
      bubbles: true,
      composed: true,
      cancelable: true,
      detail: {
        options: opts,
        result: undefined,
      }
    });
    target.dispatchEvent(e);
    return ((e.detail.result as unknown) as Promise<IOpenFileDialogResult>);
  },

  writeFile: async (path: string, contents: BufferSource | Blob | string | Buffer, opts?: FileWriteOptions, target: EventTarget = document.body): Promise<void> => {
    const e = new CustomEvent(EventTypes.Filesystem.writeFile, {
      bubbles: true,
      composed: true,
      cancelable: true,
      detail: {
        path,
        contents,
        options: opts,
        result: undefined,
      }
    });
    target.dispatchEvent(e);
    await ((e.detail.result as unknown) as Promise<void>);
  },

  readFile: async (path: string, opts?: FileReadOptions, target: EventTarget = document.body): Promise<Buffer | ArrayBuffer | string | undefined> => {
    const e = new CustomEvent(EventTypes.Filesystem.readFile, {
      bubbles: true,
      composed: true,
      cancelable: true,
      detail: {
        path,
        options: opts,
        result: undefined,
      }
    });
    target.dispatchEvent(e);
    return ((e.detail.result as unknown) as Promise<Buffer | ArrayBuffer | string>);
  },
});
