<template>
  <div class="license-activation public-page">
    <header class="info-header">
      <p class="info-header__text small-emph">Für <span class="info-header__emph">{{ me.email }}</span> haben wir keine gültige Lizenz gefunden</p>
    </header>
    <section class="coupon">
      <form
        class="license-activation__form license-activation-form"
        novalidate
        @submit.prevent="validateBeforeSubmit">
        <h2>Geben Sie einen Coupon-Code ein</h2>
        <div class="change-form__field skillboxform-input">
          <label
            for="coupon"
            class="skillboxform-input__label">Coupon-Code</label>
          <input
            v-model="coupon"
            v-validate="'required'"
            :class="{ 'skillboxform-input__input--error': errors.has('coupon') }"
            name="coupon"
            type="coupon"
            data-vv-as="Coupon"
            class="change-form__new skillbox-input skillboxform-input__input"
            autocomplete="off"
            data-cy="coupon-input"
            tabindex="0"
            id="coupon"
          >
          <small
            class="skillboxform-input__error"
            data-cy="coupon-local-errors"
            v-if="errors.has('coupon') && submitted"
          >{{ errors.first('coupon') }}</small>
          <small
            :key="error"
            class="skillboxform-input__error"
            data-cy="coupon-remote-errors"
            v-for="error in couponErrors"
          >{{ error }}</small>
        </div>
        <div class="actions">
          <loading-button
            :loading="loading"
            class="actions__submit"
            data-cy="coupon-button"
            label="Coupon abschicken"
          />
          <a
            class="button button--big"
            data-cy="license-activation-cancel"
            @click="logout">Abmelden
          </a>
        </div>
      </form>
    </section>
    <section class="get-license">
      <h2>Oder, kaufen Sie eine Lizenz</h2>
      <ul class="license-links">
        <li class="license-links__item"><a
          :href="teacherEditionUrl"
          class="hep-link">{{ pageTitle }} für Lehrpersonen</a></li>
        <li class="license-links__item"><a
          :href="studentEditionUrl"
          class="hep-link">{{ pageTitle }} für Lernende</a></li>
      </ul>
    </section>
  </div>
</template>

<script>

import REDEEM_COUPON from '@/graphql/gql/mutations/redeemCoupon.gql';
import ME_QUERY from '@/graphql/gql/queries/meQuery.gql';
import LoadingButton from '@/components/LoadingButton';

import me from '@/mixins/me';
import logout from '@/mixins/logout';
import pageTitleMixin from '@/mixins/page-title';

export default {
  mixins: [me, logout, pageTitleMixin],
  components: {LoadingButton},

  data() {
    return {
      coupon: '',
      couponErrors: [],
      loginError: '',
      submitted: false,
      me: {
        email: ''
      },
      teacherEditionUrl: `${process.env.HEP_URL}/myskillbox-lehrpersonen`,
      studentEditionUrl: `${process.env.HEP_URL}/myskillbox-fur-lernende`,
      loading: false
    };
  },
  methods: {
    validateBeforeSubmit() {
      this.$validator.validate().then(result => {
        this.submitted = true;
        let that = this;
        if (result) {
          this.loading = true;
          this.$apollo.mutate({
            mutation: REDEEM_COUPON,
            variables: {
              input: {
                couponCode: this.coupon
              }
            },
            update(
              store,
              {
                data: {coupon}
              }
            ) {
              if (coupon.success) {
                that.loading = false;
                that.couponErrors = [];
                that.$apollo.query({
                    query: ME_QUERY,
                    fetchPolicy: 'network-only',
                  }).then(() => that.$router.push('/'));
              }
            }
          }).catch(({message}) => {
            this.loading = false;
            if (message.indexOf('invalid_coupon') > -1) {
              that.couponErrors = ['Der angegebene Coupon-Code ist ungültig.'];
            } else {
              that.couponErrors = ['Es ist ein Fehler aufgetreten. Bitte versuchen Sie es nochmals oder kontaktieren Sie den Administrator.'];
            }
          })
          .finally(() => {
            this.loading = false;
          });
        }
      });
    },
    resetForm() {
      this.coupon = '';
      this.submitted = false;
      this.$validator.reset();
    }
  },
};
</script>

<style scoped lang="scss">
@import "@/styles/_variables.scss";
@import "@/styles/_mixins.scss";

.text-link {
  font-family: $sans-serif-font-family;
  color: $color-brand;
}

.actions {
  &__reset {
    display: inline-block;
    margin-left: $large-spacing;
  }
}

.get-license {
  margin-top: $large-spacing
}

.license-links {
  &__item {
    margin-bottom: $medium-spacing;
  }
}

</style>
