<script setup lang="ts">
import type {ContextMenu} from "@models/misc/contextMenu.ts";
import {menuEntryWithAction, menuEntryWithChildren} from "@models/misc/contextMenu.ts";

import {type PropType} from 'vue';

const emit = defineEmits(['contextMenuAction']);

const props = defineProps({
  top: {
    type: Number,
  },
  left: {
    type: Number,
  },
  menu: {
    type: Object as PropType<ContextMenu>,
  }
});

function triggerAction(item: string) {
  emit('contextMenuAction', item);
}
</script>

<template>
  <v-card
      class="mx-auto context-menu"
      width="200"
      ref="menuRef"
      :style="{ top: `${props.top}px`, left: `${props.left}px` }"
  >
    <v-list>
      <template v-for="(entry, i) in menu.entries">
        <v-list-group
            v-if="menuEntryWithChildren(entry) && entry.children"
            :value="i"
        >
          <template v-slot:activator="{ props }">
            <v-list-item v-bind="props" :title=entry.menuText></v-list-item>
          </template>
          <v-list-item
              v-for="(child, j) in entry.children"
              :key="j"
              @click="triggerAction(child.actionTrigger)"
              :title="child.menuText"
          ></v-list-item>
        </v-list-group>

        <!-- Render children if any -->
        <v-list-item
            v-else-if="menuEntryWithAction(entry)"
            link
            @click="triggerAction(entry.actionTrigger)"
        >
          <v-list-item-title>{{ entry.menuText }}</v-list-item-title>
        </v-list-item>
      </template>
    </v-list>
  </v-card>
</template>

<style scoped>
.context-menu {
  position: absolute;
  width: 200px
}
</style>