<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
            v-if="user.isPermittedTo('userSettings', 'write')"
            dense
            flat
            icon="add"
            @click="openAllValueDialog(null)"
          >
            <q-tooltip>{{ $t('addNewUser') }}</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('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
          :props="props"
          :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-role="props">
        <q-td :props="props">
          <q-select
            :readonly="!user.isPermittedTo('userSettings', 'write') || !autorized(props.row)"
            dense
            v-model="props.row.role"
            :options="localRoles"
            @update:model-value="updateUser(props.row)"
          ></q-select>
        </q-td>
      </template>
      <template v-slot:body-cell-expiration="props">
        <q-td
          :props="props"
          :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 === 'never' ? $t('never') : props.value }}
        </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>
  </div>
  <EditOneDialog
    ref="editOneDialog"
    query-id
    v-on:update="(val) => updateUser(val)"
  ></EditOneDialog>
  <EditAllDialog ref="editAllDialog" :roles="localRoles" 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 { roles, useRoleTable } from '../roles/RoleTable';
import { i18n } from 'src/boot/lang';
import { useUserStore } from 'src/vueLib/login/userStore';

const { NotifyResponse } = useNotify();
const editOneDialog = ref();
const editAllDialog = ref();
const okDialog = ref();
const deleteText = ref('');
const localRoles = computed(() => {
  return roles.value.map((role) => role.role);
});
const selectOption = ref(false);
const selected = ref<Users>([]);
const openSubmenu = ref(false);
const filter = ref('');
const currentUser = ref();
const { users, pagination, loading, columns, updateUsers } = useUserTable();
const { updateRoles } = useRoleTable();
const user = useUserStore();

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

//check authorization
function autorized(user: User): boolean {
  if (user.id !== 1) return true;
  return false;
}

// 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) + ' ' + i18n.global.t('users');
  }
  okDialog.value?.open(users);
}

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

  removeUsers.forEach((user: User) => {
    if (user.id === currentUser.value.id) {
      NotifyResponse(i18n.global.t('notPossibleToDeleteLoggedInUser'), 'error');
    } else if (user.id) {
      userIds.push(user.id);
    }
  });

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

// update role select
function updateUser(user: User) {
  appApi
    .post('/users/update', user)
    .then(() => NotifyResponse(i18n.global.t('userUpdated')))
    .catch((err) => NotifyResponse(err, 'error'));
}
</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>
