<template>
  <div class="q-pa-md">
    <q-table
      flat
      bordered
      ref="tableRef"
      title="Users"
      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="users"
      :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 dense flat icon="add" @click="openAllValueDialog(null)">
            <q-tooltip>{{ $t('addNewUser') }}</q-tooltip>
          </q-btn>
          <q-btn
            dense
            flat
            style="color: grey"
            :icon="selectOption ? 'check_box' : 'check_box_outline_blank'"
            @click="selectOption = !selectOption"
          >
            <q-tooltip>{{ $t('selectUserOptions') }}</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.name === 'role'" :props="props">
          <q-select dense v-model="props.row.role" :options="localRoles"></q-select>
        </q-td>
        <q-td
          v-else
          :props="props"
          @click="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 flat dense icon="delete" color="negative" @click="openRemoveDialog(props.row)">
            <q-tooltip> {{ $t('delete') }} </q-tooltip>
          </q-btn>
        </q-td>
      </template>
    </q-table>
  </div>
  <EditOneDialog ref="editOneDialog" v-on:update="updateUsers"></EditOneDialog>
  <EditAllDialog ref="editAllDialog" v-on:update="updateUsers"></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) => removeUser(...val)"
  ></OkDialog>
</template>

<script setup lang="ts">
import { appApi } from 'src/boot/axios';
import { ref, onMounted, computed } from 'vue';
import type { Users, User } from 'src/vueLib/models/users';
import EditOneDialog from 'src/components/EditOneDialog.vue';
import EditAllDialog from 'src/components/UserEditAllDialog.vue';
import OkDialog from 'src/components/dialog/OkDialog.vue';
import { useNotify } from 'src/vueLib/general/useNotify';
import { useUserTable } from './UserTable';
import { useLogin } from 'src/vueLib/login/useLogin';
import { roles } from '../roles/RoleTable';

const { NotifyResponse } = useNotify();
const editOneDialog = ref();
const editAllDialog = ref();
const okDialog = ref();
const deleteText = ref('');
const localRoles = computed(() => roles.value.map((role) => role.role));
const selectOption = ref(false);
const selected = ref<Users>([]);
const openSubmenu = ref(false);
const filter = ref('');

const { users, pagination, loading, columns, updateUsers } = useUserTable();

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

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

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

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

//remove user from database
function removeUser(...removeUsers: Users) {
  const userIds: number[] = [];

  removeUsers.forEach((user: User) => {
    if (user.id) {
      userIds.push(user.id);
    }
  });

  const login = useLogin();
  const user = login.getUser();

  appApi
    .post('secure/users/delete?id=' + user?.id, { ids: userIds })
    .then(() => {
      updateUsers();
      selected.value = [];
    })
    .catch((err) => NotifyResponse(err, 'error'))
    .finally(() => {
      loading.value = false;
    });
}

function getSelected(): Users {
  if (selected.value.length === 0) return [];
  return selected.value;
}
defineExpose({
  getSelected,
});
</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>
