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

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

  import NEW_CONTENT_BLOCK_MUTATION from '@/graphql/gql/mutations/addContentBlock.gql';
  import MODULE_DETAILS_QUERY from '@/graphql/gql/queries/modules/moduleDetailsQuery.gql';
  import {setUserBlockType} from '@/helpers/content-block';

  export default {
    components: {
      ContentsForm
    },

    data() {
      return {
        contentBlock: {
          title: '',
          contents: [
            {}
          ]
        },
        saving: false
      };
    },

    methods: {
      hideModal() {
        this.$store.dispatch('resetContentBlockPosition');
        this.$store.dispatch('hideModal');
      },
      saveContentBlock(contentBlock) {
        this.saving = true;
        this.$apollo.mutate({
          mutation: NEW_CONTENT_BLOCK_MUTATION,
          variables: {
            input: {
              contentBlock: {
                title: contentBlock.title,
                contents: contentBlock.contents.filter(value => Object.keys(value).length > 0),
                type: setUserBlockType(contentBlock.isAssignment)
              },
              after: this.$store.state.contentBlockPosition.after,
              parent: this.$store.state.contentBlockPosition.parent
            }
          },
          refetchQueries: [{
            query: MODULE_DETAILS_QUERY,
            variables: {
              slug: this.$route.params.slug
            }
          }]
        }).then(() => {
          this.saving = false;
          this.hideModal();
        });
      }
    },
  };
</script>
