<template>
  <join-form
    :value="code"
    :error="error"
    title="Einer Klasse beitreten"
    ok-text="Klasse beitreten"
    cancel-text="Abmelden"
    help-text="Den Zugangscode zur Klasse erhalten Sie von Ihrer Lehrperson."
    @input="updateCode"
    @cancel="logout"
    @confirm="joinClass"
  />
</template>

<script>
import JOIN_CLASS_MUTATION from '@/graphql/gql/mutations/joinClass.gql';
import log from 'loglevel';
import MY_SCHOOL_CLASS_QUERY from '@/graphql/gql/queries/mySchoolClass.gql';

import addSchoolClass from '@/mixins/add-school-class';
import logout from '@/mixins/logout';

import JoinForm from '@/components/profile/JoinForm.vue';

export default {
  mixins: [addSchoolClass, logout],
  components: { JoinForm },

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

  methods: {
    updateCode(event) {
      this.code = event.target.value;
      this.error = '';
    },
    joinClass(code) {
      log.debug('joining class');
      this.$apollo
        .mutate({
          mutation: JOIN_CLASS_MUTATION,
          variables: {
            input: {
              code,
            },
          },
          update: (
            store,
            {
              data: {
                joinClass: { schoolClass },
              },
            }
          ) => {
            this.addSchoolClass(store, schoolClass);
            log.debug('added school class');
            this.$router.push({ name: 'my-class' });
          },
          refetchQueries: [{ query: MY_SCHOOL_CLASS_QUERY }],
        })
        .then(() => {})
        .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.';
          }
        });
    },
  },
};
</script>
