<template>
  <div>
    <q-card-section>
      <router-link to="/" class="block">
        <img
          src="statics/banner.svg"
          alt="Verdnatura"
          class="block full-width"
        />
      </router-link>
    </q-card-section>
    <q-card-section>
      <q-form @submit="onLogin" class="q-gutter-y-md">
        <div class="q-gutter-y-sm">
          <q-input
            v-model="email"
            :label="$t('email')"
            :rules="[ val => !!val || $t('inputEmail')]"
            autofocus
            filled
          />
          <q-input
            v-model="password"
            ref="password"
            :label="$t('password')"
            :type="showPwd ? 'password' : 'text'"
            :rules="[ val => !!val || $t('inputPassword')]"
            filled>
            <template v-slot:append>
              <q-icon
                :name="showPwd ? 'visibility_off' : 'visibility'"
                class="cursor-pointer"
                @click="showPwd = !showPwd"
              />
            </template>
          </q-input>
          <q-checkbox
            v-model="remember"
            :label="$t('remember')"
            dense
          />
        </div>
        <div class="justify-center">
          <q-btn
            type="submit"
            :label="$t('enter')"
            class="full-width"
            color="primary"
          />
          <div class="text-center q-mt-xs">
            <router-link to="/remember-password" class="link">
              {{$t('notRememberPassword')}}
            </router-link>
          </div>
        </div>
      </q-form>
    </q-card-section>
    <q-card-section>
      <div class="text-center q-mb-xs text-grey-8">
        {{$t('notYetUser')}}
      </div>
      <q-btn
        :label="$t('register')"
        to="/register"
        class="full-width"
        color="grey-9"
      />
    </q-card-section>
  </div>
</template>

<style lang="stylus" scoped>
</style>

<script>
export default {
  name: 'Login',
  data () {
    return {
      email: '',
      password: '',
      remember: false,
      showPwd: true
    }
  },
  mounted () {
    if (this.$route.query.emailConfirmed !== undefined) {
      this.$q.notify({
        message: this.$t('emailConfirmedSuccessfully'),
        type: 'positive'
      })
    }
    if (this.$route.params.email) {
      this.email = this.$route.params.email
      this.$refs.password.focus()
    }
  },
  methods: {
    async onLogin () {
      const params = {
        password: this.password
      }

      if (this.email.indexOf('@') !== -1) {
        params.email = this.email
      } else {
        params.username = this.email
      }

      const res = await this.$axios.post('users/login', params)
      localStorage.setItem('token', res.data.id)
      Object.assign(this.$state.user, {
        loggedIn: true,
        token: res.data.id,
        id: res.data.userId,
        name: this.email
      })
      this.$router.push('/home')
    }
  }
}
</script>
