<template>
  <contents-form
    :content-block="entry"
    :show-task-selection="false"
    :disable-save="saving"
    data-cy="add-room-entry-modal"
    block-type="RoomEntry"
    @save="saveEntry"
    @hide="hideModal"
  />
</template>

<script>
  import NEW_ROOM_ENTRY_MUTATION from 'gql/mutations/rooms/addRoomEntry.gql';
  import ROOM_ENTRIES_QUERY from '@/graphql/gql/queries/roomEntriesQuery.gql';

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

  export default {
    components: {
      ContentsForm
    },

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

    computed: {
      room() {
        return this.$store.state.parentRoom;
      }
    },

    methods: {
      saveEntry(entry) {
        this.saving = true;
        this.$apollo.mutate({
          mutation: NEW_ROOM_ENTRY_MUTATION,
          variables: {
            input: {
              roomEntry: Object.assign({}, entry, {
                room: this.room.id
              })
            }
          },
          update: (store, {data: {addRoomEntry: {roomEntry}}}) => {
            try {
              const query = ROOM_ENTRIES_QUERY;
              const variables = {slug: this.room.slug};
              const data = store.readQuery({query, variables});
              if (data.room && data.room.roomEntries) {
                data.room.roomEntries.edges.unshift({
                  node: roomEntry,
                  __typename: 'RoomEntryNode'
                });
                store.writeQuery({query, variables, data});
              }
            } catch (e) {
              // Query did not exist in the cache, and apollo throws a generic Error. Do nothing
            }
          }
        }).then(() => {
          this.saving = false;
          this.hideModal();
        });
      },
      hideModal() {
        this.$store.dispatch('hideModal');
      },
    }
  };
</script>
