<template>
  <div class="text-black"></div>
  <q-form ref="refForm">
    <q-item-section class="q-gutter-md q-pa-md">
      <q-card :class="['q-gutter-xs q-items-center q-pa-lg', { shake: shake }]">
        <div class="text-h5 text-primary text-center">{{ productName }}</div>
        <q-input
          ref="refUserInput"
          dense
          filled
          type="text"
          :label="$t('user')"
          v-model="user"
          :rules="[(val) => !!val || $t('user') + ' ' + $t('isRequired')]"
        ></q-input>
        <q-input
          dense
          filled
          :type="showPassword ? 'text' : 'password'"
          :label="$t('password')"
          v-model="password"
          @keyup.enter="onSubmit"
          :rules="[(val) => !!val || $t('password') + ' ' + $t('isRequired')]"
        >
          <template #append>
            <q-btn
              flat
              dense
              :icon="showPassword ? 'visibility_off' : 'visibility'"
              @mousedown.left="showPassword = true"
              @mouseup.left="showPassword = false"
              @mouseleave="showPassword = false"
            ></q-btn>
          </template>
        </q-input>
        <div class="q-pt-sm q-mr-md row justify-end">
          <q-btn color="primary" :label="$t('login')" @click="onSubmit"></q-btn>
        </div>
      </q-card>
    </q-item-section>
  </q-form>
</template>

<script setup lang="ts">
import { productName } from '../../../package.json';
import { ref } from 'vue';
import { useNotify } from '../general/useNotify';
import { useLogin } from './useLogin';

const refForm = ref();
const refUserInput = ref();
const user = ref('');
const password = ref('');
const showPassword = ref(false);
const shake = ref(false);

const { NotifyResponse } = useNotify();
const { login } = useLogin();

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

const onSubmit = () => {
  refForm.value?.validate().then((success: boolean) => {
    if (success) {
      login(user.value, password.value)
        .then(() => {
          NotifyResponse("logged in as '" + user.value + "'");
          emit('update-close');
        })
        .catch((err) => {
          NotifyResponse(err, 'error');
          shake.value = true;
          setTimeout(() => {
            shake.value = false;
          }, 500);
        });
    } else {
      NotifyResponse('error submitting login form', 'error');
    }
  });
};
</script>

<style scoped>
@keyframes shake {
  0% {
    transform: translateX(0);
  }
  20% {
    transform: translateX(-8px);
  }
  40% {
    transform: translateX(8px);
  }
  60% {
    transform: translateX(-6px);
  }
  80% {
    transform: translateX(6px);
  }
  100% {
    transform: translateX(0);
  }
}

.shake {
  animation: shake 0.4s ease;
  border: 2px solid #f44336;
}
</style>
