<template>
  <DialogFrame
    ref="dialog"
    :header-title="newRole ? $t('addNewRole') : 'Edit ' + localRole.role"
    :height="600"
    :width="500"
  >
    <div class="row justify-center q-gutter-md">
      <q-input
        class="q-ml-md col-5 required"
        :label="$t('role')"
        filled
        :rules="[(val) => !!val || $t('roleIsRequired')]"
        v-model="localRole.role"
        autofocus
      ></q-input>
    </div>
    <div class="row justify-center">
      <q-btn class="q-ma-md" color="primary" no-caps @click="save">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';

const { NotifyResponse } = useNotify();
const dialog = ref();
const newRole = ref(false);
const localRole = ref<Role>({
  role: '',
  rights: null,
});

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

function open(role: Role | null) {
  if (role === undefined) {
    return;
  }

  if (role !== null) {
    localRole.value = role;
    newRole.value = false;
  } else {
    localRole.value = {
      role: '',
      rights: null,
    };
    newRole.value = true;
  }

  dialog.value?.open();
}

function save() {
  let query = 'secure/roles/edit?id=' + localRole.value.id;
  if (newRole.value) {
    query = 'secure/roles/add';
  }

  appApi
    .post(query, JSON.stringify(localRole.value))
    .then(() => {
      emit('update-role');
      dialog.value.close();
    })
    .catch((err) => NotifyResponse(err, 'error'));
}

defineExpose({ open });
</script>

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