<template>
  <DialogFrame
    ref="dialog"
    :header-title="newUser ? $t('addNewUser') : 'Edit ' + localUser.user"
    :height="600"
    :width="500"
  >
    <div class="row justify-center q-gutter-md">
      <q-input
        class="q-ml-md col-5 required"
        :label="$t('user')"
        filled
        :rules="[(val) => !!val || $t('userIsRequired')]"
        v-model="localUser.user"
        autofocus
      ></q-input>
      <q-input
        class="q-ml-md col-5 required"
        :label="$t('email')"
        filled
        :rules="[(val) => !!val || $t('emailIsRequired')]"
        v-model="localUser.email"
      ></q-input>
      <q-input
        class="q-ml-md col-5 required"
        :label="$t('role')"
        filled
        :rules="[(val) => !!val || $t('roleIsRequired')]"
        v-model="localUser.role"
      ></q-input>
      <q-input
        class="q-ml-md col-5"
        :label="$t('expires')"
        filled
        v-model="localUser.expires"
      ></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 { User } from 'src/vueLib/models/users';
import { useNotify } from 'src/vueLib/general/useNotify';

const { NotifyResponse } = useNotify();
const dialog = ref();
const newUser = ref(false);
const localUser = ref<User>({
  user: '',
  email: '',
  role: '',
  expires: '',
});

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

function open(user: User | null) {
  if (user === undefined) {
    return;
  }

  if (user !== null) {
    localUser.value = user;
    newUser.value = false;
  } else {
    localUser.value = {
      user: '',
      email: '',
      role: '',
      expires: '',
    };
    newUser.value = true;
  }

  dialog.value?.open();
}

function save() {
  let query = 'secure/users/edit?id=' + localUser.value.id;
  if (newUser.value) {
    query = 'secure/users/add';
  }

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

defineExpose({ open });
</script>

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