<template>
  <div class="attachment-info">
    <div class="attachment-info__content">
      <div v-if="loadingProof">
        <div style="font-size: 0.7em; opacity: 0.7">
          <v-progress-circular indeterminate class="mb-0"></v-progress-circular>
        </div>
      </div>
      <div v-else>
        <C2PAInfo :proof="attachment?.proof" :metadata="attachment?.mediaMetadata" :interventionFlags="attachment?.mediaInterventionFlags" :metaStripped="metaStripped" />
      </div>
    </div>
    <v-btn variant="flat" block class="attachment-info__download-button" @click.stop="() => {}">
      <v-icon color="white" class="mr-2">$vuetify.icons.ic_download</v-icon>{{ $t("cc.download_image") }}
    </v-btn>
  </div>
</template>

<script setup lang="ts">
import C2PAInfo from "../content-credentials/C2PAInfo.vue";
import { onMounted, Ref, ref } from "vue";
import { EventAttachment } from "../../models/eventAttachment";
import proofmode from "../../plugins/proofmode";
import { extractMediaMetadata } from "../../models/proof";

const { attachment } = defineProps<{
  attachment?: EventAttachment;
}>();

const loadingProof: Ref<boolean> = ref(false);
const metaStripped: Ref<boolean> = ref(false);

const updateMetaStripped = (a: EventAttachment | undefined) => {
  const hadC2PA = a?.mediaInterventionFlags ? a.mediaInterventionFlags.containsC2PA : false;
  const hadExif = a?.mediaInterventionFlags ? a.mediaInterventionFlags.containsEXIF : false;
  metaStripped.value = (hadC2PA && a?.proof?.integrity?.c2pa === undefined) || (hadExif && a?.proof?.integrity?.exif === undefined);
};

onMounted(() => {
  if ((attachment?.mediaMetadata || attachment?.mediaInterventionFlags) && attachment.proof === undefined) {
    const a = attachment;
    loadingProof.value = true;
    metaStripped.value = true;
    a.loadSrc()
      .then((data) => {
        if (data && data.data) {
          return proofmode.proofCheckSource(data.data).then((res) => {
            a.proof = res;
            if (res?.integrity?.c2pa) {
              // If we have proof, overwrite the flags
              a.mediaMetadata = extractMediaMetadata(a.proof);
            }
            updateMetaStripped(a);
          });
        }
      })
      .catch(() => {})
      .finally(() => {
        loadingProof.value = false;
      });
  } else {
    updateMetaStripped(attachment);
  }
});
</script>

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