<template>
  <div>
    <h1 data-cy="join-class-title">Zugangscode eingeben</h1>
    <div>
      <div class="skillboxform-input">
        <label for="join-code" class="skillboxform-input__label">Zugangscode</label>
        <input
          id="join-code"
          class="skillbox-input skillboxform-input__input"
          :class="{'skillboxform-input__input--error': error}"
          data-cy="input-class-code"
          :value="code"
          @input="updateCode">
        <small
          v-if="error"
          class="skillboxform-input__error"
          data-cy="email-local-errors"
        >{{ error }}
        </small>
      </div>

      <div>
        <a class="button button--primary button--big" data-cy="join-class" @click="joinClass(code)">Klasse beitreten</a>
        <a class="button button--big" data-cy="join-class-cancel" @click="cancel">Abbrechen</a>
      </div>

    </div>
  </div>
</template>

<script>
  import JOIN_CLASS_MUTATION from '@/graphql/gql/mutations/joinClass.gql';
  import ME_QUERY from '@/graphql/gql/meQuery.gql';

  export default {
    data: () => ({
      code: '',
      error: ''
    }),

    methods: {
      updateCode(event) {
        this.code = event.target.value;
        this.error = '';
      },
      joinClass(code) {
        this.$apollo.mutate({
          mutation: JOIN_CLASS_MUTATION,
          variables: {
            input: {
              code
            }
          },
          update(store, {data: {joinClass: {schoolClass}}}) {
            if (schoolClass) {
              const data = store.readQuery({query: ME_QUERY});
              if (data) {
                data.me.schoolClasses.edges.push({
                  node: schoolClass,
                  __typename: 'SchoolClassNode'
                });
                store.writeQuery({query: ME_QUERY, data});
              }
            }
          }
        })
          .then(() => {
            this.$router.push({name: 'my-class'});
          })
          .catch(e => {
            console.debug(e);
            if (e.message.indexOf('[CAJ]') > -1) {
              this.error = 'Sie sind dieser Klasse bereits beigetreten.';
            } else {
              this.error = 'Dieser Zugangscode ist nicht gültig.';
            }
          })
      },
      cancel() {
        this.$router.go(-1);
      }
    }
  }
</script>
