<template>
  <v-menu v-model="menuState" data-testid="menu" :close-on-content-click="false">
    <template #activator="{ props: menu }">
      <v-tooltip location="top">
        <template #activator="{ props: tooltip }">
          <v-btn v-bind="mergeProps(menu, tooltip)" data-testid="activator" color="white" variant="text" icon="flip" />
        </template>
        <span>{{ t('labels.flip') }}</span>
      </v-tooltip>
    </template>
    <v-list>
      <v-list-item data-testid="sagittal" @click="flipSagittal">
        <v-list-item-title>
          {{ t('labels.flipView', { view: t('enums.scanView.sagittal') }) }}
        </v-list-item-title>
      </v-list-item>
      <v-list-item data-testid="coronal" @click="flipCoronal">
        <v-list-item-title>
          {{ t('labels.flipView', { view: t('enums.scanView.coronal') }) }}
        </v-list-item-title>
      </v-list-item>
      <v-list-item data-testid="transverse" @click="flipTransverse">
        <v-list-item-title>
          {{ t('labels.flipView', { view: t('enums.scanView.transverse') }) }}
        </v-list-item-title>
      </v-list-item>
    </v-list>
  </v-menu>
</template>

<script setup lang="ts">
import { computed, mergeProps, ref } from 'vue';
import { InvertTransformData, ScanView } from '@3cr/types-ts';
import { useViewer3cr } from '@/composables/useViewer3cr';
import { useI18n } from 'vue-i18n';

interface Props {
  view: ScanView;
}

type Emits = {
  'update:modal': [value: boolean];
};

defineProps<Props>();

const emit = defineEmits<Emits>();

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

const menu = ref<boolean>(false);
const sagittal = ref<boolean>(false);
const coronal = ref<boolean>(false);
const transverse = ref<boolean>(false);

const menuState = computed({
  get(): boolean {
    return menu.value;
  },
  set(value: boolean): void {
    menu.value = value;
    emit('update:modal', value);
  }
});

async function flipSagittal(): Promise<void> {
  const value = !sagittal.value;
  await invert(value, coronal.value, transverse.value);
  sagittal.value = value;
}

async function flipCoronal(): Promise<void> {
  const value = !coronal.value;
  await invert(sagittal.value, value, transverse.value);
  coronal.value = value;
}

async function flipTransverse(): Promise<void> {
  const value = !transverse.value;
  await invert(sagittal.value, coronal.value, value);
  transverse.value = value;
}

async function invert(sagittal: boolean, coronal: boolean, transverse: boolean): Promise<void> {
  const message: InvertTransformData = {
    Version: '0.0.0',
    InvertedSagittal: sagittal,
    InvertedCoronal: coronal,
    InvertedTransverse: transverse
  };
  await viewer3cr.invertTransform({ message });
}
</script>
