<template>
  <DialogFrame
    ref="dialog"
    :header-title="newUser ? $t('addNewUser') : $t('edit') + ' ' + localUser.user"
    :height="600"
    :width="500"
  >
    <q-form ref="form">
      <div class="row justify-center q-gutter-md">
        <q-input
          class="col-5 required"
          :label="$t('user')"
          filled
          :lazy-rules="false"
          :rules="[(val) => !!val || $t('userIsRequired')]"
          v-model="localUser.user"
          autofocus
        ></q-input>
        <q-input
          class="col-5 required"
          :label="$t('email')"
          filled
          :lazy-rules="false"
          :rules="[(val) => !!val || $t('emailIsRequired')]"
          v-model="localUser.email"
        ></q-input>
        <EnterNewPassword class="col-5 required" v-model:password="localUser.password!" />
        <div class="col-5">
          <q-select
            class="col-5 required"
            :label="$t('role')"
            filled
            option-label="role"
            option-value="role"
            emit-value
            :options="props.roles"
            :rules="[(val) => !!val || $t('roleIsRequired')]"
            v-model="role"
          ></q-select>
          <q-input
            class="col-5 q-mt-xl"
            :label="$t('expires')"
            filled
            type="datetime-local"
            v-model="localUser.expiration"
          ></q-input>
        </div>
      </div>
    </q-form>
    <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 { User } from 'src/vueLib/models/users';
import { useNotify } from 'src/vueLib/general/useNotify';
import { validateQForm } from 'src/vueLib/utils/validation';
import { i18n } from 'src/boot/lang';
import { DefaultSettings } from 'src/vueLib/models/settings';
import EnterNewPassword from 'src/vueLib/login/EnterNewPassword.vue';

const { NotifyResponse } = useNotify();
const dialog = ref();
const form = ref();
const newUser = ref(false);
const role = ref('');

const localUser = ref<User>({
  user: '',
  email: '',
});

const props = defineProps({
  roles: {
    type: Array,
    required: true,
  },
});

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

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

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

  await dialog.value?.open();
  await validateQForm(form.value);
}

async function save() {
  if (!(await validateQForm(form.value))) {
    NotifyResponse(i18n.global.t('notAllRequiredFieldsFilled'), 'error');
    return;
  }
  let query = 'users/edit?id=' + localUser.value.id;
  if (newUser.value) {
    query = 'users/add';
    localUser.value.settings = DefaultSettings();
  }

  localUser.value.role = { role: role.value || '', permissions: [] };
  appApi
    .post(query, JSON.stringify(localUser.value))
    .then(() => {
      emit('update');
      dialog.value.close();
    })
    .catch((err) => NotifyResponse(err, 'error'));
}

defineExpose({ open });
</script>

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