<template>
  <DialogFrame
    ref="dialog"
    :header-title="newRole ? $t('addNewRole') : 'Edit ' + localRole.role"
    :height="700"
    :width="500"
  >
    <div class="row justify-center">
      <q-input
        v-if="showRoleField"
        class="q-my-lg col-5 required"
        :label="$t('role')"
        filled
        :rules="[(val) => !!val || $t('roleIsRequired')]"
        v-model="localRole.role"
        autofocus
      ></q-input>
      <q-card>
        <q-card-section class="text-h5 text-bold text-primary flex justify-center">{{
          $t('permissions')
        }}</q-card-section>
        <q-separator color="black" />
        <PermissionsCheckBoxGroup
          :permissions="localRole.permissions || []"
          v-on:update="(val) => (localRole.permissions = val)"
        />
      </q-card>
    </div>
    <div class="row justify-center">
      <q-btn class="q-ma-md" color="primary" no-caps @click="save">{{ $t('save') }}</q-btn>
    </div>
  </DialogFrame>
</template>

<script setup lang="ts">
import DialogFrame from 'src/vueLib/dialog/DialogFrame.vue';
import { ref } from 'vue';
import { appApi } from 'src/boot/axios';
import type { Role } from 'src/vueLib/models/roles';
import { useNotify } from 'src/vueLib/general/useNotify';
import PermissionsCheckBoxGroup from 'src/vueLib/checkboxes/CheckBoxGroupPermissions.vue';
import { defaultPermissions } from 'src/vueLib/checkboxes/permissions';
import { i18n } from 'src/boot/lang';

const { NotifyResponse } = useNotify();
const dialog = ref();
const newRole = ref(false);
const showRoleField = ref(true);
const localRole = ref<Role>({
  role: '',
  permissions: [],
});

const emit = defineEmits(['update']);

function open(role: Role | null, typ?: 'permissions') {
  if (role === undefined) {
    return;
  }

  showRoleField.value = typ !== 'permissions';
  if (role !== null) {
    localRole.value = { ...role };
    localRole.value.permissions = role.permissions || defaultPermissions;
    newRole.value = false;
  } else {
    localRole.value = {
      role: '',
      permissions: defaultPermissions,
    };
    newRole.value = true;
  }

  dialog.value?.open();
}

function save() {
  let query = 'roles/update?id=' + localRole.value.id;
  let update = true;
  if (newRole.value) {
    query = 'roles/add';
    update = false;
    localRole.value.permissions = localRole.value.permissions ?? defaultPermissions;
  }

  appApi
    .post(query, JSON.stringify(localRole.value))
    .then(() => {
      if (update) {
        NotifyResponse(
          i18n.global.t('role') + " '" + localRole.value.role + "' " + i18n.global.t('updated'),
        );
      }
      emit('update');
      dialog.value.close();
    })
    .catch((err) => NotifyResponse(err, 'error'));
}

defineExpose({ open });
</script>

<style>
.required .q-field__label::after {
  content: ' *';
  color: red;
}
</style>
