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

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

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

  const defaultAppearance = 'blue';

  export default {
    components: {
      ProjectForm
    },

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

    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.edges.unshift({
                  node: project,
                  __typename: 'ProjectNode'
                });
                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>
