<template>
  <component
    :is="rootComponent"
    ref="root"
    v-bind="{ ...$props, ...$attrs }">
    <div class="bubble image-bubble">
      <v-responsive :aspect-ratio="16 / 9" class="ma-0 pa-0" v-if="attachment">
        <video :src="attachment.src" controls class="w-100 h-100">
          {{$t('fallbacks.video_file')}}
        </video>
        <div v-if="!attachment.src && attachment.srcProgress >= 0" class="download-overlay">
          <div class="text-center download-text">
            {{ $t('message.download_progress',{percentage: attachment.srcProgress}) }}
          </div>
        </div>
        <div v-else-if="!attachment.autoDownloadable && !attachment.src" class="download-overlay">
          <div class="text-center download-text">
            {{ attachment?.name }}
          </div>
          <div class="text-center download-size">
            {{ prettyBytes(attachment.srcSize) }}
          </div>
          <v-icon size="32" color="white" class="clickable" @click="() => attachment?.loadSrc()">download</v-icon>
        </div>
      </v-responsive>
    </div>
  </component>
</template>

<script setup lang="ts">
import { computed, inject, useTemplateRef, watch } from "vue";
import MessageIncoming from "./MessageIncoming.vue";
import MessageOutgoing from "./MessageOutgoing.vue";
import { useLazyLoad } from "./useLazyLoad";
import { useI18n } from "vue-i18n";
import { MessageEmits, MessageProps, useMessage } from "./useMessage";
import { EventAttachment } from "../../../models/eventAttachment";
import prettyBytes from "pretty-bytes";

const { t } = useI18n()
const $matrix: any = inject('globalMatrix');

type RootType = InstanceType<typeof MessageOutgoing | typeof MessageIncoming>
const rootRef = useTemplateRef<RootType>("root");

const props = defineProps<MessageProps>();

const {
  isVisible
} = useLazyLoad({ root: rootRef });

const {
  isIncoming,
  attachment,
} = useMessage($matrix, t, props, undefined, undefined);

const rootComponent = computed(() => {
 return isIncoming.value ? MessageIncoming : MessageOutgoing;
})

watch([isVisible, attachment], ([_v, _a]: [_v: boolean, _a: EventAttachment | undefined]) => {
  if (_v && _a) {
    if (_a.autoDownloadable) {
      _a.loadSrc();
    }
  }
});
</script>

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