<template>
  <div class="my-class">
    <h1
      class="my-class__header"
      data-cy="class-list-title">Klassenliste</h1>
    <router-link
      :to="{name: 'show-code'}"
      class="my-class__code-link button button--primary"
      v-if="me.isTeacher">Zugangscode anzeigen
    </router-link>
    <class-list
      :name="me.selectedClass.name"
      :members="me.selectedClass.members"
      :teacher="me.isTeacher"
      :id="me.selectedClass.id"
      class="my-class__class"
      @remove="remove"
      @add="add"
    />
  </div>
</template>

<script>
  import ClassList from '@/components/profile/ClassList';

  import MY_SCHOOL_CLASS_QUERY from '@/graphql/gql/mySchoolClass.gql';
  import ADD_REMOVE_MEMBER_MUTATION from '@/graphql/gql/mutations/addRemoveMember.gql';
  import selectedClassMixin from '@/mixins/selected-class';

  export default {
    mixins: [selectedClassMixin],

    components: {
      ClassList
    },

    methods: {
      changeMember(member, active) {
        this.$apollo.mutate({
          mutation: ADD_REMOVE_MEMBER_MUTATION,
          variables: {
            input: {
              member: member.id,
              schoolClass: this.me.selectedClass.id,
              active
            }
          },
          update(store, {data: {addRemoveMember: {success}}}) {
            if (success) {
              const query = MY_SCHOOL_CLASS_QUERY;
              const data = store.readQuery({query});
              let memberIndex = data.me.selectedClass.members.findIndex(m => m.id === member.id);
              data.me.selectedClass.members = [
                ...data.me.selectedClass.members.slice(0, memberIndex),
                {...member, active},
                ...data.me.selectedClass.members.slice(memberIndex + 1),
              ];
              store.writeQuery({query, data});
            }
          }
        });
      },
      add(member) {
        this.changeMember(member, true);
      },
      remove(member) {
        this.$modal.open('deactivate-person', {
          myself: member.id === this.me.id,
          name: `${member.firstName} ${member.lastName}`,
          className: this.me.selectedClass.name,
        })
          .then(() => {
            this.changeMember(member, false);
          })
          .catch(() => {
          });
      }
    },
  };
</script>

<style scoped lang="scss">
  @import "@/styles/_variables.scss";

  .my-class {
    display: grid;
    grid-template-columns: auto auto;
    grid-template-rows: auto auto;
    grid-template-areas: "h b" "c c";

    &__header {
      grid-area: h;
    }

    &__code-link {
      grid-area: b;
      justify-self: end;
      align-self: center;
    }

    &__class {
      grid-area: c;
      width: 100%;
      margin-bottom: $large-spacing;
    }
  }

</style>
