<template lang='pug'>
form#reset(autocomplete="off", @submit.prevent="submitForm" method="post")
  b-form-group
    .msg
      h3 \{{ $t('login.reset_password') }}
  b-form-group
    vm-input(type="password" icon='lock-outline', :placeholder='$t("login.password")' v-model="form.password" required show-strength-meter showPasswordLabel :passwordLabels="passwordLabels" pass)

  b-form-group
    vm-button#loginButton.vm-con-loading__container(:disabled="$v.form.$invalid" color="primary", type="filled")  \{{ $t('login.reset_password') }}
  .back
    router-link.content-vertical.text-secondary(to='/login') \{{ $t('login.still_having_trouble') }}
</template>

<script>
import { required, minLength, email, sameAs } from 'vuelidate/lib/validators'
import checkResponse from '@/utils/checkResponse'
import { mapActions } from 'vuex'

export default {
  name: 'reset-link',
  data () {
    return {
      form: {
        token: '',
        email: ''
      },
      passwordLabels: [
        this.$t('passwords.very_weak'),
        this.$t('passwords.weak'),
        this.$t('passwords.good'),
        this.$t('passwords.strong'),
        this.$t('passwords.very_strong')
      ]
    }
  },
  validations: {
    form: {
      password: {
        required,
        minLength: minLength(8)
      },
      password_confirmation: {
        required,
        sameAsPassword: sameAs('password')
      },
      email: {
        required,
        email
      },
      token: {
        required
      }
    }
  },
  async mounted () {
    this.form.token = this.$route.params.token
    this.form.email = this.$route.query.email
  },
  methods: {
    ...mapActions([
      'setAlertMessage'
    ]),
    async doSubmit () {
      const response = await this.axios.post('../password/reset', this.form)
      const checkErrors = checkResponse(response)
      if (checkErrors) {
        this.setAlertMessage({ color: 'danger', title: 'errors.connection_error', text: checkErrors.message })
        return
      }
      this.setAlertMessage({ color: 'success', title: 'login.reset_password', text: 'passwords.reset' })
      this.$router.push({ name: 'login' })
    },
    async submitForm (evt) {
      this.$vm.loading({
        background: 'primary',
        color: '#fff',
        container: '#loginButton',
        scale: 0.45
      })
      try {
        await this.doSubmit()
      } catch (error) {
        this.setAlertMessage({ color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' })
      }
      this.$vm.loading.close('#loginButton > .con-vm-loading')
    }
  },
  watch: {
    'form.password' (pass) {
      this.form.password_confirmation = pass
    }
  }
}
</script>

<style lang="scss" scoped>
.msg {
  text-align: center;
  margin-top: 10px;
}
#loginButton {
  width: 100%;
}
.back{
  color: rgb(107, 119, 140);
  padding-top: 24px;
  margin-top: 10px;
  font-size: 14px;
  text-align: center;
  line-height: 20px;
  border-top: 1px solid rgb(213, 216, 222);
}
</style>
