<template>
  <v-dialog v-model="modelValue" persistent width="535">
    <v-card class="position-relative">
      <v-card-title class="pt-4 pl-6 pb-2">
        <span>{{ t('labels.annotationUpdate') }}</span>
      </v-card-title>
      <v-btn
        variant="text"
        icon="close"
        color="shark_400"
        @click="modelValue = false"
        class="position-absolute"
        style="top: 0; right: 0"
      />
      <v-card-text class="pb-1 pt-0">
        <AnnotationForm v-model="proxy" />
      </v-card-text>
      <v-card-actions class="px-6 pb-4">
        <v-spacer />
        <v-btn color="minsk_900" variant="plain" @click="modelValue = false">
          <span>{{ t('labels.cancel') }}</span>
        </v-btn>
        <v-btn class="px-4 py-2" color="minsk_900" variant="flat" @click="update">
          <span>{{ t('labels.update') }}</span>
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { useViewer3cr } from '@/composables/useViewer3cr';
import AnnotationForm from '@/components/navigation/annotation/AnnotationForm.vue';
import { ref, watch } from 'vue';
import { DataOverlayAnnotation } from '@3cr/viewer-types-ts';

interface Props {
  annotation: DataOverlayAnnotation;
}

const props = defineProps<Props>();

const { t } = useI18n();
const viewer3cr = useViewer3cr();

const proxy = ref<DataOverlayAnnotation>();
const isUpdating = ref<boolean>(false);

const modelValue = defineModel<boolean>({ default: false });

watch(
  () => props.annotation,
  (value) => {
    if (!isUpdating.value) {
      proxy.value = JSON.parse(JSON.stringify(value));
    }
  },
  { immediate: true }
);

async function update(): Promise<void> {
  isUpdating.value = true;

  const id = proxy.value!.Id;

  const titleMessage = { Version: '0.0.0', Id: id, Value: proxy.value!.Title };
  await viewer3cr.updateAnnotationTitle({ message: titleMessage });

  const descMessage = { Version: '0.0.0', Id: id, Value: proxy.value!.Description };
  await viewer3cr.updateAnnotationDescription({ message: descMessage });

  const actions = proxy.value!.CallToAction!.Actions.map((a) => ({
    ActionType: a.ActionType,
    ActionData: JSON.stringify(a.ActionData)
  }));
  const actionsMessage = { Version: '0.0.0', Id: id, Value: JSON.stringify({ Actions: actions }) };
  await viewer3cr.updateAnnotationActions({ message: actionsMessage });

  const iconMessage = { Version: '0.0.0', Id: id, Icon: proxy.value!.Icon2d };
  await viewer3cr.setAnnotationIcon({ message: iconMessage });

  const colour2dMessage = { Version: '0.0.0', Id: id, Colour: proxy.value!.Colour2d };
  await viewer3cr.setAnnotation2dColour({ message: colour2dMessage });

  const colour3dMessage = { Version: '0.0.0', Id: id, Colour: proxy.value!.Colour3d };
  await viewer3cr.setAnnotation3dColour({ message: colour3dMessage });

  isUpdating.value = false;
  modelValue.value = false;
}
</script>
