<template>
  <section class="hero is-info is-fullheight-with-navbar">
    <div class="hero-body">
      <div class="container">
        <div class="box" v-if="!$store.state.emailVerified">
          <article class="media">
            <div class="media-content">
              <center>
                <i class="fas fa-envelope-open" style="color:#0a8bff; font-size: 30px;"></i>
                <div class="content">
                  <h1>Let's verify your account shall we?</h1>
                  <p>This page allows you to verify your account with the link provided in the email.</p>
                  <a v-bind:href="$route.params.out"><b-button @click="verifyEmail" :loading="verification.loading" class="is-warning-passive">Yes, Verify my account.</b-button></a>
                </div>
              </center>
            </div>
          </article>
        </div>
        <div class="box" v-if="$store.state.emailVerified">
          <article class="media">
            <div class="media-content">
              <center>
                <i class="fas fa-envelope-open" style="color:#0a8bff; font-size: 30px;"></i>
                <div class="content">
                  <h1>Your account is already verified.</h1>
                  <p>You can't verify your email twice!</p>
                </div>
              </center>
            </div>
          </article>
        </div>
      </div>
    </div>
  </section>
</template>
<script>
import logger from "../../assets/js/logger";

export default {
  name: 'verification',
  data() {
    return {
      token: '',
      verification: {
        loading: false
      }
    }
  },
  methods: {
    verifyEmail () {
        this.verification.loading = true

        this.axios.get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `users/email-verify/` + this.$route.query.token).then(res => {
          this.verification.loading = false
          this.$store.commit('setAdmin', res.data.admin)
        }).then(() => {
          this.verification.loading = false
          this.$router.push(`/verify/success`)
        }).catch(err => {
          this.verification.loading = false
          this.$router.push('/verify/error')
          this.ajaxErrorHandler(err)
        })
      }
    },
  watch: {
    created() {
      if (this.$route.query.token) {
        this.$store.commit('setEmailToken', this.$route.query.emailToken)
      }
    },
  },
  mounted () {
    this.$store.dispatch('setTitle', 'Email Verification')
    this.axios.get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'userinfo')
      .then(res => {
        this.$store.commit('setUsername', res.data.username)
        this.$store.commit('setEmail', res.data.email)
        this.$store.commit('setEmailVerified', res.data.emailVerified)
        this.$store.commit('setAdmin', res.data.admin)
      })
      .catch(e => {
        this.showConn(e)
      })
    logger('settingsAccount')
  }
}
</script>
