<template>
  <join-form
    :value="name"
    class="create-class"
    title="Klasse erfassen"
    ok-text="Klasse erfassen"
    label-text="Name"
    :error="error"
    cancel-text="Abbrechen"
    @input="updateName"
    @cancel="cancel"
    @confirm="createClass"
  />
</template>

<script>
import addSchoolClassMixin from '@/mixins/add-school-class';

import CREATE_CLASS_MUTATION from '@/graphql/gql/mutations/createClass.gql';
import JoinForm from '@/components/profile/JoinForm';

export default {
  mixins: [addSchoolClassMixin],

  components: {
    JoinForm,
  },

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

  methods: {
    updateName(event) {
      this.name = event.target.value;
      this.error = '';
    },
    createClass(name) {
      this.$apollo.mutate({
        mutation: CREATE_CLASS_MUTATION,
        variables: {
          input: {
            name,
          },
        },
        update: (
          store,
          {
            data: {
              createSchoolClass: { result },
            },
          }
        ) => {
          if (result.__typename === 'DuplicateName') {
            this.error = result.reason;
          } else {
            this.addSchoolClass(store, result);
            this.$router.push({
              name: 'my-class',
            });
          }
        },
      });
    },
    cancel() {
      this.$router.go(-1);
    },
  },
};
</script>

<style scoped lang="scss">
@import '~styles/helpers';

.create-class {
}
</style>
