<template>
  <div class="q-pa-md">
    <q-table
      flat
      bordered
      ref="tableRef"
      title="Events"
      title-class="text-bold text-blue-9"
      :no-data-label="$t('noDataAvailable')"
      :loading-label="$t('loading')"
      :rows-per-page-label="$t('recordsPerPage')"
      :selected-rows-label="(val) => val + ' ' + $t('recordSelected')"
      :rows="Events"
      :columns="columns"
      row-key="id"
      v-model:pagination="pagination"
      :loading="loading"
      :filter="filter"
      :selection="selectOption ? 'multiple' : 'none'"
      v-model:selected="selected"
      binary-state-sort
      class="bigger-table-text"
    >
      <template v-slot:top-left>
        <q-btn-group push flat style="color: grey">
          <q-btn
            v-if="user.isPermittedTo('events', 'write')"
            dense
            flat
            icon="add"
            @click="openAllValueDialog(null)"
          >
            <q-tooltip>{{ $t('addNewEvent') }}</q-tooltip>
          </q-btn>
          <q-btn
            v-if="user.isPermittedTo('events', 'write')"
            dense
            flat
            style="color: grey"
            :icon="selectOption ? 'check_box' : 'check_box_outline_blank'"
            @click="selectOption = !selectOption"
          >
            <q-tooltip>{{ $t('selectEventOptions') }}</q-tooltip>
          </q-btn>
        </q-btn-group>
        <div v-if="selectOption && selected.length > 0">
          <q-btn flat dense icon="more_vert" @click="openSubmenu = true" />
          <q-menu v-if="openSubmenu" anchor="bottom middle" self="top middle">
            <q-item
              clickable
              v-close-popup
              @click="openRemoveDialog(...selected)"
              class="text-negative"
              >{{ $t('delete') }}</q-item
            >
          </q-menu>
        </div>
        <div v-if="selectOption && selected.length > 0" class="q-ml-md text-weight-bold">
          {{ $t('selected') }}: {{ selected.length }}
        </div>
      </template>
      <template v-slot:top-right>
        <q-input filled dense debounce="300" v-model="filter" :placeholder="$t('search')">
          <template v-slot:append>
            <q-icon name="search" />
          </template>
        </q-input>
      </template>
      <template v-slot:body-cell="props">
        <q-td v-if="props.col.field === 'attendees'" :props="props">
          <q-btn dense flat icon="people" @click="openAttendees(props.row)"
            ><q-badge color="primary" text-color="primary-text" floating transparent>{{
              props.row.count
            }}</q-badge></q-btn
          >
        </q-td>
        <q-td
          v-else
          :props="props"
          :style="
            user.isPermittedTo('events', 'write') && props.col.field !== 'count'
              ? 'cursor: pointer'
              : ''
          "
          @click="
            user.isPermittedTo('events', 'write') &&
            props.col.field !== 'count' &&
            openSingleValueDialog(props.col.label, props.col.name, props.row)
          "
        >
          {{ props.value }}
        </q-td>
      </template>
      <template v-slot:body-cell-option="props">
        <q-td :props="props">
          <q-btn
            v-if="user.isPermittedTo('events', 'write') || user.isPermittedTo('events', 'delete')"
            flat
            dense
            icon="more_vert"
            @click="openSubmenu = true"
          />
          <q-menu v-if="openSubmenu" anchor="top right" self="top left">
            <q-item
              v-if="user.isPermittedTo('events', 'write')"
              clickable
              v-close-popup
              @click="openAllValueDialog(props.row)"
              class="text-primary"
              >{{ $t('edit') }}</q-item
            >
            <q-item
              v-if="user.isPermittedTo('events', 'delete')"
              clickable
              v-close-popup
              @click="openRemoveDialog(props.row)"
              class="text-negative"
              title="zu"
              >{{ $t('delete') }}</q-item
            >
          </q-menu>
        </q-td>
      </template>
    </q-table>
  </div>
  <EditOneDialog
    ref="editOneDialog"
    endpoint="events/edit"
    query-id
    v-on:update="updateEvents"
  ></EditOneDialog>
  <EditAllDialog ref="editAllDialog" v-on:update="updateEvents"></EditAllDialog>
  <AttendeesTable ref="attendeesDialog" v-on:update="updateEvents" />
  <OkDialog
    ref="okDialog"
    :dialog-label="$t('delete')"
    :text="$t('doYouWantToDelete') + ' ' + deleteText"
    label-color="red"
    :button-cancel-label="$t('cancel')"
    :button-ok-label="$t('confirm')"
    :button-ok-flat="false"
    button-ok-color="red"
    v-on:update-confirm="(val) => removeEvent(...val)"
  ></OkDialog>
</template>

<script setup lang="ts">
import { appApi } from 'src/boot/axios';
import { ref, onMounted } from 'vue';
import type { Event, Events } from 'src/vueLib/models/event';
import EditOneDialog from 'src/components/EditOneDialog.vue';
import EditAllDialog from 'src/components/EventEditAllDialog.vue';
import OkDialog from 'src/components/dialog/OkDialog.vue';
import { useNotify } from 'src/vueLib/general/useNotify';
import { useEventTable } from './EventsTable';
import { databaseName } from '../members/MembersTable';
import { useUserStore } from 'src/vueLib/login/userStore';
import AttendeesTable from '../attendees/AttendeesTable.vue';
import type { Members } from 'src/vueLib/models/member';

export interface EventDialog {
  getSelected: () => Events;
}

const { NotifyResponse } = useNotify();
const editOneDialog = ref();
const editAllDialog = ref();
const attendeesDialog = ref();
const okDialog = ref();
const deleteText = ref('');
const selectOption = ref(false);
const selected = ref<Events>([]);
const openSubmenu = ref(false);
const filter = ref('');
const user = useUserStore();

const { Events, pagination, loading, columns, updateEvents } = useEventTable();

//load on mounting page
onMounted(() => {
  loading.value = true;

  appApi
    .post('database/open', { dbPath: databaseName.value, create: true })
    .then(() => {
      updateEvents();
    })
    .catch((err) => NotifyResponse(err, 'error'))

    .finally(() => {
      loading.value = false;
    });
});

// opens dialog for all Event values
function openSingleValueDialog(label: string, field: string, Event: Event) {
  editOneDialog.value?.open(label, field, Event);
}

//opens dialog for one value
function openAllValueDialog(Event: Event | null) {
  editAllDialog.value?.open(Event);
}

//opens remove dialog
function openRemoveDialog(...Events: Events) {
  if (Events.length === 1) {
    deleteText.value = "'";
    if (Events[0]?.name !== undefined) {
      deleteText.value += Events[0]?.name + ' ';
    }
    deleteText.value += "'";
  } else {
    deleteText.value = String(Events.length) + ' Events';
  }
  okDialog.value?.open(Events);
}

function openAttendees(attendees: Members | null) {
  attendeesDialog.value.open(attendees);
}

//remove Event from database
function removeEvent(...removeEvents: Events) {
  const EventIds: number[] = [];

  removeEvents.forEach((Event: Event) => {
    EventIds.push(Event.id);
  });

  appApi
    .post('events/delete', { ids: EventIds })
    .then(() => {
      updateEvents();
      selected.value = [];
    })
    .catch((err) => NotifyResponse(err, 'error'))
    .finally(() => {
      loading.value = false;
    });
}
</script>

<style>
@keyframes blink-yellow {
  0%,
  100% {
    background-color: yellow;
  }
  50% {
    background-color: transparent;
  }
}

.blink-yellow {
  animation: blink-yellow 1.5s step-start 6 !important;
}

.bigger-table-text .q-table__middle td {
  font-size: 14px;
}

.bigger-table-text .q-table__top,
.bigger-table-text .q-table__bottom,
.bigger-table-text th {
  font-size: 14px;
}
</style>
