<template>
  <objective-group-form
    :title="title"
    :objectives="objectives"
    @save="saveObjectiveGroup"
    @hide="hideModal"
  ></objective-group-form>
</template>

<script>
  import Modal from '@/components/Modal';
  import ObjectiveGroupForm from '@/components/objective-groups/ObjectiveGroupForm';
  import AddContentElement from '@/components/AddContentElement';

  import UPDATE_OBJECTIVE_GROUP_MUTATION from '@/graphql/gql/mutations/updateObjectiveGroup.gql';
  import MODULE_DETAILS_QUERY from '@/graphql/gql/moduleDetailsQuery.gql';
  import OBJECTIVE_GROUP_QUERY from '@/graphql/gql/objectiveGroupQuery.gql';

  export default {
    components: {
      AddContentElement,
      Modal,
      ObjectiveGroupForm
    },

    computed: {
      title() {
        if (this.$store.state.objectiveGroupType === 'society') {
          return 'Gesellschaft';
        }
        return 'Sprache & Kommunikation';
      },
      objectives() {
        return this.objectiveGroup.objectives.edges.map(edge => edge.node)
      }
    },

    methods: {
      saveObjectiveGroup(objectives) {
        const objectiveGroup = {
          id: this.$store.state.currentObjectiveGroup,
          objectives,
        };
        this.$apollo.mutate({
          mutation: UPDATE_OBJECTIVE_GROUP_MUTATION,
          variables: {
            input: {
              objectiveGroup
            }
          },
          // todo: make update work
          // update: (store, {data: {addObjectiveGroup: {objectiveGroup}}}) => {
          //   const query = MODULE_DETAILS_QUERY;
          //   const variables = {slug: this.$route.params.slug};
          //   const data = store.readQuery({query, variables});
          //   debugger;
          //   if (data.module && data.module.objectiveGroups) {
          //     data.module.objectiveGroups.edges.push({
          //       node: objectiveGroup,
          //       __typename: 'ObjectiveGroupNode'
          //     });
          //     store.writeQuery({query, variables, data});
          //   }
          //
          // }
          refetchQueries: [{
            query: MODULE_DETAILS_QUERY,
            variables: {
              slug: this.$route.params.slug
            }
          }]

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

    apollo: {
      objectiveGroup() {
        return {
          query: OBJECTIVE_GROUP_QUERY,
          variables: {
            id: this.$store.state.currentObjectiveGroup
          }
        }
      }
    },

    data() {
      return {
        objectiveGroup: {
          objectives: {
            edges: []
          }
        }
      }
    }
  }
</script>

<style scoped lang="scss">

</style>
