<template>
  <module :module="module" v-if="module.id" :edit="editModule"></module>
</template>

<script>
  import {mapGetters, mapActions} from 'vuex'
  import ASSIGNMENTS_QUERY from '@/graphql/gql/assignmentsQuery.gql';
  import MODULE_DETAILS_QUERY from '@/graphql/gql/moduleDetailsQuery.gql';

  import SCROLL_POSITION from '@/graphql/gql/local/scrollPosition.gql';
  import SCROLL_TO_MUTATION from '@/graphql/gql/local/mutations/scrollTo.gql';

  import Module from '@/components/modules/Module.vue';

  export default {
    components: {
      Module
    },

    methods: {
      ...mapActions(['scrollToAssignmentReady', 'scrollingToAssignment']),
      scrollTo() {
        if (this.scrollPosition && this.scrollPosition.scrollTo) {
          let options = {
            container: 'body',
            easing: 'ease',
            offset: -60,
            onStart: (element) => {
            },
            onDone: (element) => {
            },
            onCancel: function () {
              // scrolling has been interrupted
            },
            x: false,
            y: true
          };
          setTimeout(() => {
            this.$scrollTo(`[data-scrollto="${this.scrollPosition.scrollTo}"]`, 1000, options);
            this.$apollo.mutate({
              mutation: SCROLL_TO_MUTATION,
              variables: {
                scrollTo: ''
              }
            })
          }, 250); // unfortunately this timeout is needed as it is hard to tell when everything is rendered
        }
      }
    },

    computed: {
      ...mapGetters({
        editModule: 'editModule'
      }),
    },

    apollo: {
      module() {
        return {
          query: MODULE_DETAILS_QUERY,
          variables: {
            slug: this.$route.params.slug
          },
          update(data) {
            return this.$getRidOfEdges(data).module || {};
          },
          result() {
            // scroll only after the module has been loaded completely
            this.scrollTo();
          }
        }
      },
      assignments() {
        return {
          query: ASSIGNMENTS_QUERY
        }
      },
      scrollPosition: {
        query: SCROLL_POSITION
      },
    },

    data() {
      return {
        module: {},
        assignments: []
      }
    },
  }
</script>
