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

    <template #footer>
      <div>
        <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>
    </template>
  </modal>
</template>

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

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

export default {
  components: {
    Modal,
    ModalInput,
  },

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

  computed: {
    objectiveGroup() {
      return this.$modal.state.payload.parent;
    },
    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 { objectiveGroup } = store.readQuery({ query, variables });
              if (objectiveGroup && objectiveGroup.objectives) {
                const objectives = [
                  ...objectiveGroup.objectives,
                  {
                    ...objective,
                    __typename: 'ObjectiveNode',
                  },
                ];
                const data = {
                  objectiveGroup: {
                    ...objectiveGroup,
                    objectives,
                  },
                };
                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.$modal.confirm();
        });
    },
    hide() {
      this.$modal.cancel();
    },
  },
};
</script>
