<template>
  <div>
    <app-loader v-if="!authFailed" overlay>
      <h2>Authenticating...</h2>
    </app-loader>
    <app-message v-if="authFailed" :description="err.errorDescription" message="Failed to authenticate.">
      <template slot="extras">
        <Button type="primary" @click="triggerLogin">Log in</Button>
      </template>
    </app-message>
  </div>
</template>

<script>
import auth from "~/utils/auth";

export default {
  data() {
    return {
      authFailed: false,
      err: {}
    };
  },
  mounted() {
    auth
      .handleAuthentication()
      .then(this.authorized)
      .catch(this.unauthorized);
  },
  methods: {
    authorized({ returnUrl }) {
      this.$router.replace(returnUrl);
    },
    unauthorized(err) {
      this.authFailed = true;
      this.err = err;
    },
    triggerLogin() {
      const errorState =
        this.err && this.err.state ? JSON.parse(this.err.state) : null;
      const returnUrl =
        errorState && errorState.returnUrl ? errorState.returnUrl : "/";
      auth.triggerLogin({ returnUrl });
    }
  }
};
</script>

