<template>
  <div>
    <plugin-table-action-icon v-if="canAdd" :is-add="true" title="Add Row" @click="onClick('add')" />
    <plugin-table-action-icon v-if="canDelete" :is-add="false" title="Delete this row" @click="onClick('remove')" />
  </div>
</template>

<script setup lang="ts">
import { createEmptyJoinTable } from '@/js/helper';
import type { SavedData } from '@/types/model';
import { defineProps, withDefaults, inject } from 'vue';

const props = withDefaults(
  defineProps<{
    canAdd?: boolean;
    canDelete?: boolean;
    tableId: string;
  }>(),
  {
    canAdd: true,
    canDelete: true,
  },
);

const savedData = inject<SavedData>('savedData') as SavedData;
const onClick = (type: 'add' | 'remove') => {
  if (type === 'add') {
    const currentIndex = savedData.joinTables.findIndex((t) => t.id === props.tableId);
    if (currentIndex !== -1) {
      savedData.joinTables.splice(currentIndex + 1, 0, createEmptyJoinTable());
    } else {
      savedData.joinTables.push(createEmptyJoinTable());
    }
  } else if (savedData.joinTables.length > 1) {
    savedData.joinTables = savedData.joinTables.filter((t) => t.id !== props.tableId);
  }
};
</script>
