<template>
  <modal :hide-header="true">
    <modal-input
      :placeholder="'Lernziel'"
      :value="text"
      @input="text = $event"
    />

    <div slot="footer">
      <a
        :class="{'button--disabled': disableSave}"
        class="button button--primary"
        data-cy="modal-save-button"
        @click="save(text)">Speichern</a>
      <a
        class="button"
        @click="hide()">Abbrechen</a>
    </div>
  </modal>
</template>

<script>
  import Modal from '@/components/Modal';
  import ModalInput from '@/components/ModalInput';

  import NEW_OBJECTIVE_MUTATION from '@/graphql/gql/mutations/addObjective.gql';
  import OBJECTIVE_GROUP_QUERY from '@/graphql/gql/queries/objectiveGroupQuery.gql';

  import {mapGetters} from 'vuex';

  export default {
    components: {
      Modal,
      ModalInput
    },

    data() {
      return {
        text: '',
        saving: false
      };
    },

    computed: {
      ...mapGetters({
        objectiveGroup: 'currentObjectiveGroup'
      }),
      disableSave() {
        return this.saving;
      }
    },

    methods: {
      save(entry) {
        this.saving = true;
        this.$apollo.mutate({
          mutation: NEW_OBJECTIVE_MUTATION,
          variables: {
            input: {
              objective: Object.assign({}, {
                objectiveGroup: this.objectiveGroup,
                text: entry
              })
            }
          },
          update: (store, {data: {addObjective: {objective}}}) => {
            try {
              const query = OBJECTIVE_GROUP_QUERY;
              const variables = {id: this.objectiveGroup};
              const data = store.readQuery({query, variables});
              if (data.objectiveGroup && data.objectiveGroup.objectives) {
                data.objectiveGroup.objectives.push({
                  ...objective,
                  __typename: 'ObjectiveNode'
                });
                store.writeQuery({query, variables, data});
              }
            } catch (e) {
              // Query did not exist in the cache, and apollo throws a generic Error. Do nothing
            }
          }
        }).then(() => {
          this.saving = false;
          this.hide();
        });
      },
      hide() {
        this.$store.dispatch('hideModal');
      }
    }
  };
</script>
