<template>
  <edit-name-wizard
    :name="name"
    type="Klasse"
    @input="name = $event"
    @cancel="hideModal"
    @save="save" />
</template>

<script>
  import MY_SCHOOL_CLASS_QUERY from '@/graphql/gql/queries/mySchoolClass.gql';
  import UPDATE_SCHOOL_CLASS_MUTATION from '@/graphql/gql/mutations/updateSchoolClass.gql';
  import EditNameWizard from '@/components/profile/EditNameWizard';

  export default {
    components: {
      EditNameWizard,
    },

    data() {
      return {
        name: ''
      };
    },

    mounted() {
      this.name = this.schoolClass ? this.schoolClass.name : '';
    },

    methods: {
      save() {
        this.$apollo.mutate({
          mutation: UPDATE_SCHOOL_CLASS_MUTATION,
          variables: {
            input: {
              name: this.name,
              id: this.schoolClass.id
            }
          },
          update(store, {data: {updateSchoolClass: {schoolClass: {name}}}}) {
            const query = MY_SCHOOL_CLASS_QUERY;
            const data = store.readQuery({query});
            data.me.selectedClass.name = name;
            store.writeQuery({query, data});
          }
        });
        this.hideModal();
      },
      hideModal() {
        this.$store.dispatch('hideModal');
      }
    },

    apollo: {
      schoolClass: {
        query: MY_SCHOOL_CLASS_QUERY,
        update(data) {
          return this.$getRidOfEdges(data).me.selectedClass;
        }
      }
    },
  };
</script>
