<template>
  <modal class="new-objective-group-wizard">
    <template slot="header">
      <h4 class="new-objective-group-wizard__heading">Lernziele: {{title}}</h4>
    </template>

    <objective-form
      :objective="objective"
      v-for="(objective, index) in objectives"
      @input="updateObjective($event, index)"
      :key="index"></objective-form>
    <add-content-element @add-element="addObjective"></add-content-element>

    <div slot="footer">
      <a class="button button--primary" data-cy="modal-save-button" @click="saveObjectiveGroup">Speichern</a>
      <a class="button" @click="hideModal">Abbrechen</a>
    </div>

  </modal>
</template>

<script>
  import Modal from '@/components/Modal';
  import ObjectiveForm from '@/components/objective-groups/ObjectiveForm';
  import AddContentElement from '@/components/AddContentElement';

  export default {
    components: {
      AddContentElement,
      Modal,
      ObjectiveForm
    },

    computed: {
      title() {
        if (this.$store.state.objectiveGroupType === 'society') {
          return 'Gesellschaft';
        }
        return 'Sprache & Kommunikation';
      }
    },

    methods: {
      addObjective() {
        this.objectives.push({});
      },
      updateObjective(value) {
        console.log(value);
      },
      saveObjectiveGroup() {
        console.log('saving');
        this.$apollo.mutate({
          mutation: NEW_OBJECTIVE_GROUP_MUTATION,
          variables: {
            input: {
              roomEntry: Object.assign({}, this.objectives, {
                room: this.room.id
              })
            }
          },
          update: (store, {data: {addRoomEntry: {roomEntry}}}) => {
            try {
              const query = ROOM_ENTRIES_QUERY;
              const variables = {slug: this.room.slug};
              const data = store.readQuery({query, variables});
              if (data.room && data.room.roomEntries) {
                data.room.roomEntries.edges.unshift({
                  node: roomEntry,
                  __typename: 'RoomEntryNode'
                });
                store.writeQuery({query, variables, data});
              }
            } catch (e) {
              // Query did not exist in the cache, and apollo throws a generic Error. Do nothing
            }
          }
        }).then(() => {
          this.hideModal();
        });
      },
      hideModal() {
        this.$store.dispatch('hideModal');
      },
    },

    data() {
      return {
        objectives: [
          {},
        ]
      }
    }
  }
</script>

<style scoped lang="scss">
  .new-objective-group-wizard {
    &__heading {
      margin-bottom: 0;
    }
  }
</style>
