<template>
  <project-entry-form
    :project-entry="projectEntry"
    @save="save"
    @hide="hideModal"/>
</template>

<script>
  import ProjectEntryForm from './ProjectEntryForm';

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

  export default {
    components: {
      ProjectEntryForm
    },

    data() {
      return {
        projectEntry: {
          description: '',
          documentUrl: ''
        }
      };
    },

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

    methods: {
      save(entry) {
        this.$apollo.mutate({
          mutation: NEW_PROJECT_ENTRY_MUTATION,
          variables: {
            input: {
              projectEntry: Object.assign({
                project: this.project
              }, entry)
            }
          },
          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.push(projectEntry);
              store.writeQuery({query, variables, data});
            }
          }

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