<template>
  <modal :hide-header="true">
    <div class="project-entry-modal">
      <text-form-with-help-text title="Tätigkeit" :value="activity" @change="activity = $event">
      </text-form-with-help-text>
      <text-form-with-help-text title="Reflexion" :value="reflection" @change="reflection = $event">
      </text-form-with-help-text>
      <text-form-with-help-text title="Nächste Schritte" :value="nextSteps" @change="nextSteps = $event">
      </text-form-with-help-text>
    </div>
    <div slot="footer">
      <a class="button button--primary" data-cy="modal-save-button" v-on:click="save">Speichern</a>
      <a class="button" v-on:click="hideModal">Abbrechen</a>
    </div>
  </modal>
</template>

<script>
  import Modal from '@/components/Modal';
  import TextFormWithHelpText from '@/components/content-forms/TextFormWithHelpText';

  import NEW_PROJECT_ENTRY_MUTATION from '@/graphql/gql/mutations/addProjectEntry.gql';
  import PROJECT_QUERY from '@/graphql/gql/projectQuery.gql';

  export default {
    components: {
      Modal,
      TextFormWithHelpText
    },

    computed: {
      project() {
        return this.$store.state.parentProject;
      },
      slug() {
        return this.$route.params.slug;
      }
    },

    methods: {
      save() {
        this.$apollo.mutate({
          mutation: NEW_PROJECT_ENTRY_MUTATION,
          variables: {
            input: {
              projectEntry: Object.assign({}, {
                nextSteps: this.nextSteps,
                activity: this.activity,
                reflection: this.reflection,
                project: this.project
              })
            }
          },
          update: (store, {data: {addProjectEntry: {projectEntry}}}) => {
            const query = PROJECT_QUERY;
              const variables = {slug: this.slug};
              const data = store.readQuery({query, variables});
              if (data.project && data.project.entries) {
                data.project.entries.edges.unshift({
                  node: projectEntry,
                  __typename: 'ProjectEntryNode'
                });
                store.writeQuery({query, variables, data});
              }
          }

        }).then(() => {
          this.hideModal();
        });
      },
      hideModal() {
        this.$store.dispatch('hideModal');
      }
    },

    data() {
      return {
        activity: '',
        reflection: '',
        nextSteps: ''
      }
    }
  }
</script>
