<template>
  <div @click="click">
    <input enctype="multipart/form-data" ref="file" name="files" :multiple="multiple" type="file" hidden
      @change="upload">
    <slot></slot>
  </div>
</template>

<script lang="ts" setup>
import { fs } from '@veypi/oaer';


let file = ref<HTMLInputElement>()
let emits = defineEmits<{
  (e: 'success', v: string): void
  (e: 'failed'): void
}>()
let props = withDefaults(defineProps<{
  multiple?: boolean,
  renames?: string,
  dir?: string,
}>(), {
  multiple: false,
  dir: '/',
  renames: ''
})

function click() {
  file.value?.dispatchEvent(new MouseEvent('click'))
}

const upload = (evt: Event) => {
  evt.preventDefault()
  let dir = props.dir
  if (!dir.endsWith('/')) {
    dir = dir + '/'
  }
  let f = (evt.target as HTMLInputElement).files as FileList
  for (let i = 0; i < f.length; i++) {
    let name = dir + fs.rename(f[i].name)
    f[i].arrayBuffer().then((v) => {
      fs.app.putFileContents(name, v).then((e) => {
        emits('success', fs.app.urlwrap(name))
      }).catch((e) => {
        console.log(e)
        emits('failed')
      })
    })
  }
  console.log(f)
  // oafs.upload(f, props.dir, props.renames?.split(/[, ]+/)).then((e: any) => {
  //   console.log(e)
  //   emits('success', props.multiple ? e : e[0])
  // })
}


</script>

<style scoped></style>
