<template>
  <DialogFrame
    ref="dialog"
    :header-title="$t('changePassword') + ' ' + $t('user') + ' ' + localUser.user"
    :height="510"
    :width="500"
    :inner-padding="48"
  >
    <q-form ref="form">
      <div class="row justify-center q-gutter-md">
        <q-input
          class="col-6 required"
          filled
          autocomplete="current-password"
          :type="showPassword ? 'text' : 'password'"
          :label="$t('currentPassword')"
          v-model="localUser.password"
          :rules="[(val) => !!val || $t('currentPassword') + ' ' + $t('isRequired')]"
        >
          <template #append>
            <q-btn
              flat
              dense
              :icon="showPassword ? 'visibility_off' : 'visibility'"
              @mousedown.prevent="showPassword = true"
              @mouseup.prevent="showPassword = false"
              @mouseleave.prevent="showPassword = false"
              @touchstart.prevent="showPassword = true"
              @touchend.prevent="showPassword = false"
              @touchcancel.prevent="showPassword = false"
            ></q-btn>
          </template>
        </q-input>
        <div class="col-6">
          <EnterNewPassword v-model:password="localUser.newPassword!" />
        </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 { ref } from 'vue';
import DialogFrame from '../dialog/DialogFrame.vue';
import type { User } from 'src/vueLib/models/users';
import { i18n } from 'src/boot/lang';
import { useNotify } from '../general/useNotify';
import { validateQForm } from '../utils/validation';
import EnterNewPassword from './EnterNewPassword.vue';

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

const open = (user: User) => {
  localUser.value = user;
  localUser.value.password = '';
  localUser.value.newPassword = '';
  dialog.value?.open();
};

const close = () => {
  dialog.value?.close();
};

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

async function save() {
  if (!(await validateQForm(form.value))) {
    NotifyResponse(i18n.global.t('notAllRequiredFieldsFilled'), 'error');
    return;
  }
  emit('update:password', localUser.value);
}

defineExpose({ open, close });
</script>
