<template>
  <join-form
    :value="code"
    :error="error"
    title="Einer Klasse beitreten"
    ok-text="Klasse beitreten"
    cancel-text="Abmelden"
    @input="updateCode"
    @cancel="logout"
    @confirm="joinClass"/>
</template>

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

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

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

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

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

    methods: {
      updateCode(event) {
        this.code = event.target.value;
        this.error = '';
      },
      joinClass(code) {
        this.$log.debug('joining class');
        this.$apollo.mutate({
            mutation: JOIN_CLASS_MUTATION,
            variables: {
              input: {
                code,
              },
            },
            update: (store, {data: {joinClass: {schoolClass}}}) => {
              this.addSchoolClass(store, schoolClass);
              this.$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>
