<template>
  <project-form
    :project="project"
    @save="saveProject"
  />
</template>

<script>
  import ProjectForm from '@/components/portfolio/ProjectForm';

  import ADD_PROJECT_MUTATION from '@/graphql/gql/mutations/addProject.gql';
  import PROJECTS_QUERY from '@/graphql/gql/queries/allProjects.gql';

  export default {
    components: {
      ProjectForm
    },

    computed: {
      project() {
        return {
          title: '',
          description: '',
          objectives: '',
        };
      }
    },

    methods: {
      saveProject(project) {
        this.$apollo.mutate({
          mutation: ADD_PROJECT_MUTATION,
          variables: {
            input: {
              project: project
            }
          },
          update: (store, {data: {addProject: {project}}}) => {
            try {
              const data = store.readQuery({query: PROJECTS_QUERY});
              if (data.projects) {
                data.projects.unshift(project);
                store.writeQuery({query: PROJECTS_QUERY, data});
              }
            } catch (e) {
              // Query did not exist in the cache, and apollo throws a generic Error. Do nothing
            }
          }
        }).then(() => {
          this.$router.push('/portfolio');
        });
      }
    }
  };
</script>
