<script setup lang="ts">
import { joinURL } from 'ufo';

const runtimeConfig = useRuntimeConfig();
const cdnUrl = runtimeConfig.public.cdn_url;

const route = useRoute();

const emit = defineEmits(['mediaload']);

const props = defineProps<{
  mediaPath: string | null | undefined;
  phase: string;
}>();

const media = computed(() => {
  const dotSplit = props.mediaPath?.split('.');
  const extension = dotSplit?.pop()?.toLowerCase();
  let type = null;
  if (extension === 'jpg') {
    type = 'image';
  } else if (extension === 'wmv') {
    type = 'video';
  }
  return { name: dotSplit?.join('.'), type };
});

const video = ref();

function onVideoLoad() {
  if (route.path === '/exam') {
    video.value.play();
    let duration = video.value.duration;
    if (isNaN(duration) || duration == Infinity) {
      duration = 0;
    }
    setTimeout(() => {
      emit('mediaload');
    }, duration * 1000);
  }
}
</script>

<template>
  <div
    class="select-none flex-auto w-full *:object-contain *:w-full *:h-full *:max-h-full relative *:absolute"
    :class="route.path === '/exam' ? 'z-[-1]' : ''"
  >
    <img v-if="phase == 'set-basic'" src="/placeholder.svg" alt="placeholder" />
    <NuxtImg
      v-else-if="media.type === 'image'"
      :key="`${mediaPath}-image`"
      provider="selfhost"
      :src="'/' + mediaPath"
      :alt="mediaPath ?? ''"
      @load="emit('mediaload')"
    />
    <video
      v-else-if="media.type === 'video'"
      :key="`${mediaPath}-video`"
      ref="video"
      :controls="route.path === '/result'"
      @canplaythrough="onVideoLoad()"
    >
      <source :src="joinURL(cdnUrl, media.name + '.mp4')" type="video/mp4" />
    </video>
    <span v-else class="text-5xl font-bold flex items-center justify-center"
      >Pytanie bez wizualizacji</span
    >
  </div>
</template>
