<template>
  <q-table
    flat
    bordered
    ref="tableRef"
    title="Roles"
    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="roles"
    :columns="columns"
    row-key="id"
    v-model:pagination="pagination"
    :loading="loading"
    :filter="filter"
    :selection="selectOption ? 'multiple' : 'none'"
    v-model:selected="selected"
    binary-state-sort
    dense
    class="bigger-table-text"
  >
    <template v-slot:top-left>
      <q-btn-group push flat style="color: grey">
        <q-btn
          v-if="user.isPermittedTo('userSettings', 'write')"
          dense
          flat
          icon="add"
          @click="openAllValueDialog(null)"
        >
          <q-tooltip>{{ $t('addNewRole') }}</q-tooltip>
        </q-btn>
        <q-btn
          v-if="user.isPermittedTo('userSettings', 'write')"
          dense
          flat
          style="color: grey"
          :icon="selectOption ? 'check_box' : 'check_box_outline_blank'"
          @click="selectOption = !selectOption"
        >
          <q-tooltip>{{ $t('selectRoleOptions') }}</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>

    <!-- top right of table-->

    <template v-slot:top-right>
      <SearchableInput v-model="filter" :placeholder="$t('search')" />
    </template>

    <!-- table body content-->

    <template v-slot:body-cell="props">
      <q-td
        :props="props"
        :disable="!autorized(props.row)"
        :style="
          autorized(props.row) && user.isPermittedTo('userSettings', 'write')
            ? 'cursor: pointer'
            : ''
        "
        @click="
          autorized(props.row) && user.isPermittedTo('userSettings', 'write')
            ? openSingleValueDialog(props.col.label, props.col.name, props.row)
            : ''
        "
      >
        {{ props.value }}
      </q-td>
    </template>
    <template v-slot:body-cell-permissions="props">
      <q-td :props="props">
        <q-btn
          :disable="!autorized(props.row) || !user.isPermittedTo('userSettings', 'write')"
          flat
          dense
          icon="rule"
          :color="
            autorized(props.row) && user.isPermittedTo('userSettings', 'write')
              ? 'secondary'
              : 'grey'
          "
          @click="
            user.isPermittedTo('userSettings', 'write') &&
            openAllValueDialog(props.row, 'permissions')
          "
        >
          <q-tooltip> {{ $t('permissions') }} </q-tooltip>
        </q-btn>
      </q-td>
    </template>
    <template v-slot:body-cell-option="props">
      <q-td :props="props">
        <q-btn
          v-if="user.isPermittedTo('userSettings', 'delete')"
          :disable="!autorized(props.row)"
          flat
          dense
          icon="delete"
          color="negative"
          @click="openRemoveDialog(props.row)"
        >
          <q-tooltip> {{ $t('delete') }} </q-tooltip>
        </q-btn>
      </q-td>
    </template>
  </q-table>
  <EditOneDialog
    ref="editOneDialog"
    endpoint="roles/update"
    query-id
    v-on:update="updateRoles"
  ></EditOneDialog>
  <EditAllDialog ref="editAllDialog" v-on:update="updateRoles"></EditAllDialog>
  <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) => removeRole(...val)"
  ></OkDialog>
</template>

<script setup lang="ts">
import { appApi } from 'src/boot/axios';
import { ref, onMounted } from 'vue';
import type { Roles, Role } from 'src/vueLib/models/roles';
import EditOneDialog from 'src/components/EditOneDialog.vue';
import EditAllDialog from 'src/components/RoleEditAllDialog.vue';
import OkDialog from 'src/components/dialog/OkDialog.vue';
import { useNotify } from 'src/vueLib/general/useNotify';
import { useRoleTable } from './RoleTable';
import { i18n } from 'src/boot/lang';
import { QTable } from 'quasar';
import { useUserStore } from 'src/vueLib/login/userStore';
import SearchableInput from '../components/SearchableInput.vue';

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

const { roles, pagination, loading, columns, updateRoles } = useRoleTable();

//load on mounting page
onMounted(() => {
  loading.value = true;
  currentUser.value = user.user;
  updateRoles().catch((err) => NotifyResponse(err, 'error'));
});

function autorized(role: Role): boolean {
  if (role.id !== 1) return true;
  return false;
}

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

//opens dialog for one value
function openAllValueDialog(role: Role | null, typ?: 'permissions') {
  editAllDialog.value?.open(role, typ);
}

//opens remove dialog
function openRemoveDialog(...roles: Roles) {
  if (roles.length === 1) {
    deleteText.value = "'" + roles[0]?.role + "'";
  } else {
    deleteText.value = String(roles.length) + ' ' + i18n.global.t('roles');
  }
  okDialog.value?.open(roles);
}

//remove role from database
function removeRole(...removeRoles: Roles) {
  const roles: string[] = [];

  removeRoles.forEach((role: Role) => {
    if (role.role === currentUser.value.role) {
      NotifyResponse(i18n.global.t('notPossibleToDeleteLoggedInRole'), 'error');
    } else if (role.role) {
      roles.push(role.role);
    }
  });

  appApi
    .post('roles/delete?role=' + currentUser.value.role, { roles: roles })
    .then(() => {
      updateRoles().catch((err) => NotifyResponse(err, 'error'));
      if (roles.length === 1) {
        NotifyResponse("'" + roles[0] + "' " + i18n.global.t('deleted'), 'warning');
      } else {
        NotifyResponse(i18n.global.t('deleteRoles'), 'warning');
      }
      selected.value = [];
    })
    .catch((err) => NotifyResponse(err, 'error'))
    .finally(() => {
      loading.value = false;
    });
}
</script>

<style>
.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>
