<template >
  <ods-form data-id="login-form" class="login-form__form" :model="loginForm" :rules="rules" ref="loginForm">
    <div>
      <h1 data-id="form-title" class="login-form__title">
        {{ $t('login.title') }}
        <div class="login-form__errors ods-mb-5">
          <ods-alert
            data-id="error-alert"
            v-if="errors"
            :title="errorInfo || $t('login.loginError')"
            type="error"
            :closable="false"
          />
        </div>
      </h1>
      <ods-form-item data-id="user-label" :label="$t('login.user')" prop="user">
        <ods-input data-id="user-input" :class="{error: errors}" type="text" v-model="loginForm.user"/>
      </ods-form-item>
      <ods-form-item data-id="pass-label" class="ods-mb-3" :label="$t('login.password')" prop="password">
        <ods-input data-id="pass-input" :class="{error: errors}" type="password" v-model="loginForm.password"/>
      </ods-form-item>
      <router-link to="/login/password" tag="div">
        <ods-button data-id="forget-pass" class="ods-p-0" type="text">{{ $t('login.forgotPassword') }}</ods-button>
      </router-link>
    </div>
    <div class="login-form__actions">
      <ods-checkbox data-id="keep-logged" v-model="keepMeLogged">{{ $t('login.keepMeLogged') }}</ods-checkbox>
      <ods-button
        data-id="submit-form"
        type="primary"
        native-type="submit"
        @click.prevent="validateForm('loginForm')"
      >{{ $t('login.login') }}</ods-button>
    </div>
  </ods-form>
</template>

<script>
import {mapActions} from 'vuex';
import FormStyles from '@/components/login/LoginFormStyles.vue';

export default {
  name: 'LoginForm',
  mixins: [FormStyles],
  data() {
    return {
      loginForm: {
        user: '',
        password: '',
      },
      rules: {
        user: [{required: true, message: this.$t('login.rules.user'), trigger: 'submit'}],
        password: [{required: true, message: this.$t('login.rules.password'), trigger: 'submit'}],
      },
      keepMeLogged: true,
      errors: false,
      errorInfo: '',
    };
  },
  methods: {
    ...mapActions([
      'login',
      'loader',
    ]),
    validateForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await this.submitForm();
        } else {
          this.errors = true;
        }
      });
    },
    async submitForm() {
      this.loader({loader: true});

      const data = {
        username: this.loginForm.user,
        password: this.loginForm.password,
      };

      const response = await this.login(data);
      const isError = response instanceof Error;

      this.$notify.closeAll();
      this.loader({loader: false});

      if (!isError) {
        sessionStorage.setItem('userId', response.name);
        sessionStorage.setItem('sessionToken', response.access_token);

        this.$router.push({name: 'Home'});
      } else {
        this.errors = true;
        this.errorInfo = `${this.$t('login.loginError')}`;

        this.$notify({
          title: this.$t('login.loginErrorTitle'),
          message: this.errorInfo,
          type: 'error',
          position: 'top-right',
          duration: 5000,
        });
      }
    },
  },
};
</script>
