// Native file picker. Ported from worker/src/utils/openFilePicker.ts; resolves to File handle(s)
// (see runtime/fetch.ts) that can be appended to a FormData and uploaded.

import { File } from "./fetch"

type OpenFilePickerOptions = { accept?: string }

export function openFilePicker(options?: OpenFilePickerOptions & { multiple?: false }): Promise<File | null>
export function openFilePicker(options: OpenFilePickerOptions & { multiple: true }): Promise<File[]>
export function openFilePicker(
  options: OpenFilePickerOptions & { multiple?: boolean } = {},
): Promise<File | File[] | null> {
  return new Promise((resolve, reject) => {
    _creatorUtils.openFilePicker((resp) => {
      if (!resp || resp.length === 0) {
        resolve(options.multiple ? [] : null)
        return
      }
      if (options.multiple) resolve(resp.map((i: any) => new File(i[0], i[1], i[2])))
      else resolve(new File(resp[0][0], resp[0][1], resp[0][2]))
    }, reject, !!options.multiple, options.accept)
  })
}
