<script setup lang="ts">
import { defineProps, defineExpose, ref } from "vue";
import { isErrorResponse, FS } from "@/api";
import { NProgress } from "naive-ui";
import filesize from "filesize";

const props = defineProps<{
  file: File;
}>();

const progress = ref(0);
const percentage = ref(0);
const err = ref("");
const status = ref("info");

async function startUpload(parent: number, token: string) {
  const resp = await FS.upload_file(token, parent, props.file, (e) => {
    progress.value = e.loaded;
    percentage.value = (e.loaded / e.total) * 100;
  });
  percentage.value = 100;
  if (isErrorResponse(resp)) {
    err.value = resp.message ?? "Error";
    status.value = "error";
  } else status.value = "success";
}

defineExpose({
  startUpload,
});
</script>

<template>
  <div v-if="percentage < 100">
    {{ file.name }} - {{ filesize(progress) }} / {{ filesize(file.size) }} -
    {{ Math.floor(percentage * 1000) / 1000 }}%
  </div>
  <div v-else-if="err !== ''">{{ file.name }} - Error: {{ err }}</div>
  <div v-else>{{ file.name }} - Completed</div>
  <n-progress
    type="line"
    :percentage="percentage"
    :height="20"
    :status="status"
    border-radius="10px 0"
    fill-border-radius="10px 0"
    :show-indicator="false"
  />
</template>

<style scoped></style>
