<template>
  <q-menu
    v-if="hasQMenu() && canDisplayQMenu"
    transition-show="jump-down"
    transition-hide="jump-up"
    class="border-k-accent no-shadow bg-k-white text-k-accent"
    square
    context-menu
    test-id="rightClickMenu"
  >
    <q-list style="min-width: 100px">
      <div v-for="group in pageActions" :key="group.title">
        <q-item
          v-if="(group as KettalFunctionAction | KettalPopupAction).selection === 'single' && canBeSingleSelected(rowData.row, group.actionSelectionRules)"
          :key="group.title"
          v-close-popup
          clickable
          :test-id="group.title + 'Menu'"
          @click="
            () => {
              $emit('activeActionFromRow', group, rowData.row);
            }
          "
        >
          <q-item-section> {{ $t(group.title) }}</q-item-section>
        </q-item>
        <q-item
          v-for="action in group.content.filter((action) => {
            return (
              action.selection === 'single' &&
              canBeSingleSelected(rowData.row, action.actionSelectionRules)
            );
          })"
          v-else-if="group.type === 'expand'"
          :key="action.title"
          v-close-popup
          clickable
          :test-id="action.title + 'Menu'"
          @click="
            () => {
              $emit('activeActionFromRow', action, rowData.row);
            }
          "
        >
          <q-item-section> {{ $t(action.title) }}</q-item-section>
        </q-item>
      </div>
    </q-list>
  </q-menu>
</template>
<script setup lang="ts">
import {
  KettalFunctionAction,
  KettalPageActions,
  KettalPopupAction,
  KettalQTableColumn,
  TableRow,
} from "@/types";

const rowData = defineModel<{ cols: KettalQTableColumn[]; row: TableRow }>(
  "rowData",
  { required: true }
);
const { pageActions } = defineProps<{
  canDisplayQMenu: boolean;
  pageActions: KettalPageActions[];
}>();
defineEmits(["activeActionFromRow"]);

function hasQMenu() {
  const hasAnySingleAction = pageActions.some((group) => {
    return (
      ((group as KettalFunctionAction | KettalPopupAction).selection ===
        "single" &&
        canBeSingleSelected(rowData.value.row, group.actionSelectionRules)) ||
      (group.type === "expand" &&
        group.content.some((action) => {
          return (
            action.selection === "single" &&
            canBeSingleSelected(rowData.value.row, action.actionSelectionRules)
          );
        }))
    );
  });
  return hasAnySingleAction;
}

function canBeSingleSelected(
  row: TableRow,
  actionSelectionRules?: (row: TableRow) => boolean
) {
  if (!actionSelectionRules) {
    return true;
  }
  return actionSelectionRules(row);
}
</script>
