<template>
  <contents-form
    :content-block="contentBlock"
    :show-task-selection="true"
    @save="saveContentBlock"
    @hide="hideModal"
  />
</template>

<script>
  import ContentsForm from '@/components/content-block-form/ContentsForm';

  import store from '@/store/index';

  import EDIT_CONTENT_BLOCK_MUTATION from 'gql/mutations/editContentBlock.gql';
  import MODULE_DETAILS_QUERY from '@/graphql/gql/queries/modules/moduleDetailsQuery.gql';
  import CONTENT_BLOCK_QUERY from '@/graphql/gql/queries/contentBlockQuery.gql';
  import { setUserBlockType } from '@/helpers/content-block';

  export default {
    components: {
      ContentsForm
    },

    data() {
      return {
        contentBlock: {}
      };
    },

    created() {
      // debugger;
    },

    methods: {
      hideModal() {
        this.$store.dispatch('resetCurrentNoteBlock');
        this.$store.dispatch('hideModal');
      },
      saveContentBlock(contentBlock) {
        this.$apollo.mutate({
          mutation: EDIT_CONTENT_BLOCK_MUTATION,
          variables: {
            input: {
              contentBlock: {
                title: contentBlock.title,
                contents: contentBlock.contents.filter(value => Object.keys(value).length > 0),
                type: setUserBlockType(contentBlock.isAssignment)
              },
              id: contentBlock.id
            }
          },
          refetchQueries: [{
            query: MODULE_DETAILS_QUERY,
            variables: {
              slug: this.$route.params.slug
            }
          }]
        }).then(() => {
          this.hideModal();
        });
      }
    },

    apollo: {
      contentBlock() {
        return {
          query: CONTENT_BLOCK_QUERY,
          variables: {
            id: store.state.currentNoteBlock
          }
        };
      }
    }

  };
</script>
