<template>
  <div ref="thumbnailRef" style="width: 100%; height: 100%">
    <v-responsive v-if="isVideo && (source || poster)" :class="{ 'thumbnail-item': true, preview: previewOnly }">
      <video :src="source" :poster="poster" :controls="!previewOnly" class="w-100 h-100">
        {{ $t("fallbacks.video_file") }}
      </video>
    </v-responsive>
    <ImageWithProgress
      v-else-if="isImage"
      :aspect-ratio="previewOnly ? 16 / 9 : undefined"
      :class="{ 'thumbnail-item': true, preview: previewOnly }"
      :src="source"
      :contain="!previewOnly"
      :cover="previewOnly"
      :loadingProgress="loadingProgress"
    />
    <div v-else :class="{ 'thumbnail-item': true, preview: previewOnly, 'file-item': true }">
      <v-icon :class="fileTypeIconClass">{{ fileTypeIcon }}</v-icon>
      <div class="file-name">{{ $$sanitize(fileName) }}</div>
      <div class="file-size">{{ fileSize }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { singleOrDoubleTapRecognizer } from "../../plugins/touch";
import { computed, inject, onBeforeUnmount, onMounted, Ref, ref, useTemplateRef, watch } from "vue";
import { EventAttachment } from "../../models/eventAttachment";
import { useThumbnail } from "../messages/composition/useThumbnail";
import { Attachment } from "../../models/attachment";
import ImageWithProgress from "../ImageWithProgress.vue";

const $$sanitize: any = inject("globalSanitize");

const thumbnailRef = useTemplateRef("thumbnailRef");

interface ThumbnailProps {
  item?: EventAttachment;
  file?: Attachment;
  previewOnly?: boolean;
}

type ThumbnailEmits = {
  (event: "itemclick", value: { item: EventAttachment }): void;
};

const props = defineProps<ThumbnailProps>();
const { item, file, previewOnly = false } = props;
const emits = defineEmits<ThumbnailEmits>();

let { isVideo, isImage, fileTypeIcon, fileTypeIconClass, fileName, fileSize } = useThumbnail(file?.file ?? item?.event);
const fileURL: Ref<string | undefined> = ref(undefined);
const source: Ref<string | undefined> = ref(undefined);
const poster: Ref<string | undefined> = ref(undefined);

const updateSource = () => {
  if (props.item) {
    if (isVideo.value || props.item.src) {
      source.value = props.item.src;
    } else if (previewOnly) {
      props.item.loadThumbnail().then((url) => { 
        source.value = url.data;
      })
    } else if (isImage.value) {
      props.item.loadSrc().then((url) => { 
        source.value = url.data;
      })
    }
  } else if (props.file) {
    if (fileURL.value) {
      URL.revokeObjectURL(fileURL.value);
    }
    fileURL.value = URL.createObjectURL(props.file.file);
    source.value = fileURL.value;
  } else {
    source.value = undefined;
  }
};

const updatePoster = () => {
  if (props.item && isVideo.value) {
    if (props.item.thumbnail) {
      poster.value = props.item.thumbnail;
    } else {
      props.item
        .loadThumbnail()
        .then((url) => {
          poster.value = url.data;
        })
        .catch(() => {
          poster.value = undefined;
        });
    }
  }
};

updateSource();
updatePoster();


watch(props, (props: ThumbnailProps) => {
  const updates = useThumbnail(props.file?.file ?? props.item?.event);
  isVideo.value = updates.isVideo.value;
  isImage.value = updates.isImage.value;
  fileTypeIcon = updates.fileTypeIcon;
  fileTypeIconClass = updates.fileTypeIconClass;
  fileName = updates.fileName;
  fileSize = updates.fileSize;
  updateSource();
  updatePoster();
});

const loadingProgress = computed(() => {
  if (item) {
    return previewOnly ? item.thumbnailProgress : item.srcProgress;
  }
  return -1;
});

onMounted(() => {
  if (thumbnailRef.value && (item as EventAttachment)) {
    const hammerInstance = singleOrDoubleTapRecognizer(thumbnailRef.value);
    hammerInstance.on("singletap doubletap", (ev: any) => {
      if (ev.type === "singletap") {
        emits("itemclick", { item: item as EventAttachment });
      }
    });
  }
  if (!previewOnly && item && (item as EventAttachment)) {
    (item as EventAttachment).loadSrc();
  }
});

onBeforeUnmount(() => {
  if (fileURL.value) {
    URL.revokeObjectURL(fileURL.value);
    fileURL.value = undefined;
  }
});
</script>

<style lang="scss">
@use "@/assets/css/chat.scss" as *;

.thumbnail-item {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.6rem;
  flex-direction: column;
  padding: 20px;
  .v-icon {
    margin-bottom: 10px;
    color: currentColor;
  }
}
</style>
