<template>
  <div>
    <video
      v-if="type === MetaType.video"
      controls
      autoplay
      playsinline
      webkit-playsinline
    >
      <source :src="url" />
    </video>
    <iframe v-else-if="type === MetaType.other" :src="url"></iframe>
    <iframe
      v-else-if="type === MetaType.xfile"
      :src="`./xfile-viewer/index.html?file=${url}&time=${Date.now()}`"
    ></iframe>
    <img :src="url" v-if="type === MetaType.image" />
    <audio
      :src="url"
      v-if="type === MetaType.audio"
      controls
      autoplay
      playsinline
      webkit-playsinline
    />
  </div>
</template>

<script lang="ts" setup>
import { getResource } from "@/env";
import { computed } from "vue";
import { getUrlType, MetaType } from "@/utils/meta";

const props = defineProps<{ data: string | Blob | File; type?: MetaType }>();

const url = computed(() =>
  typeof props.data === "string"
    ? getResource(props.data)
    : URL.createObjectURL(props.data)
);

const type = computed(() => {
  if (props.type) {
    return props.type;
  } else if (props.data instanceof File || typeof props.data === "string") {
    const d = props.data instanceof File ? props.data.name : props.data;
    return getUrlType(d);
  } else {
    return MetaType.other;
  }
});
</script>

<style scoped>
div {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
audio,
iframe {
  width: 100%;
  height: 100%;
  display: block;
}

video,
img {
  max-width: 100%;
  max-height: 100%;
  display: block;
  object-fit: cover;
}

iframe {
  border: none;
}
</style>
