<template>
  <Uploader
    ref="uploaderRef"
    v-bind="props"
    :maxUploadCount="single ? 1 : maxUploadCount"
    @updateList="handleListChange"
  />
</template>

<script setup lang="ts">
import { onMounted, ref, toRef } from 'vue';
import { useFieldChildValueInjector } from './FormContext';
import type { UploaderInstance, UploaderProps } from './Uploader.vue';
import { stringUrlToUploaderItem, type UploaderItem } from './Uploader';
import Uploader from './Uploader.vue';

export interface UploaderFieldProps extends Omit<UploaderProps, 'value'> {
  modelValue?: string[]|string;
  single?: boolean;
}

const uploaderRef = ref<UploaderInstance>();
const emit = defineEmits([ 'update:modelValue' ]);
const props = withDefaults(defineProps<UploaderFieldProps>(), {
  modelValue: undefined,
  showDelete: true,
  showUpload: true,
  uploadWhenAdded: true,
});

const {
  value,
  updateValue,
} = useFieldChildValueInjector(
  toRef(props, 'modelValue'), 
  (v) => emit('update:modelValue', v),
  undefined,
  //() => { /*uploaderRef.value?.pick()*/ },
);

function handleListChange(list: UploaderItem[]) {
  updateValue(list.map((item) => item.uploadedPath).filter((item) => item) as string[]);
}

onMounted(() => {
  setTimeout(() => {
    uploaderRef.value?.setList(props.single || typeof value.value === 'string' 
      ? (value.value ? [ stringUrlToUploaderItem(value.value as any as string) ] : [])
      : value.value?.map((item) => stringUrlToUploaderItem(item)) ?? []
    )
  }, 200);
});

defineExpose({
  getUploaderRef: () => uploaderRef.value,
})

export interface UploaderFieldInstance {
  getUploaderRef: () => UploaderInstance;
}

defineOptions({
  options: {
    styleIsolation: "shared",
    virtualHost: true,
  }
})
</script>