import { computed, ref } from "vue";
import { KeanuEvent } from "../../../models/eventAttachment";
import utils from "@/plugins/utils";
import prettyBytes from "pretty-bytes";

export const useThumbnail = (source: KeanuEvent | File | undefined) => {
  const isVideo = ref(false);
  const isImage = ref(false);
  const isAPK = ref(false);
  const isIPA = ref(false);
  const isPDF = ref(false);
  const isZip = ref(false);
  const isChannelMessage = ref(false);
  const fileName = ref("");
  const fileSize = ref("");

  function isEvent(source: KeanuEvent | File | undefined): source is KeanuEvent {
    return (source as KeanuEvent)?.getId !== undefined;
  }

  if (isEvent(source)) {
    const event = source;
    isVideo.value = event.getContent().msgtype == "m.video";
    isImage.value = event.getContent().msgtype == "m.image";
    isAPK.value = utils.isFileTypeAPK(event);
    isIPA.value = utils.isFileTypeIPA(event);
    isPDF.value = utils.isFileTypePDF(event);
    isZip.value = utils.isFileTypeZip(event);
    isChannelMessage.value = event.isChannelMessage ?? false;
    fileName.value = utils.getFileName(event);
    fileSize.value = utils.getFileSizeFormatted(event);
  } else if (source) {
    const file = source as File;
    isVideo.value = file.type.startsWith("video/");
    isImage.value = file.type.startsWith("image/");
    fileName.value = file.name;
    fileSize.value = prettyBytes(file.size);
  }

  const fileTypeIcon = computed(() => {
    if (isAPK.value) {
      if (isChannelMessage.value) {
        return "$vuetify.icons.ic_channel_apk";
      }
      return "$vuetify.icons.ic_apk";
    } else if (isIPA.value) {
      return "$vuetify.icons.ic_ipa";
    } else if (isPDF.value) {
      if (isChannelMessage.value) {
        return "$vuetify.icons.ic_channel_pdf";
      }
      return "$vuetify.icons.ic_pdf";
    } else if (isZip.value) {
      return "$vuetify.icons.ic_zip";
    }
    return "description";
  });

  const fileTypeIconClass = computed(() => {
    if (isZip.value) {
      return "zip";
    }
    return undefined;
  });

  return {
    isVideo,
    isImage,
    fileTypeIcon,
    fileTypeIconClass,
    fileName,
    fileSize,
    isPDF
  };
};
