<template>
  <content-block-form :content-block="roomEntry" :features="features" v-if="roomEntry.id" @save="save" @back="goBack" />
</template>

<script>
  import {defineComponent} from 'vue';

import ROOM_ENTRY_QUERY from 'gql/queries/roomEntryQuery.gql';
import ROOM_ENTRY_FRAGMENT from 'gql/fragments/roomEntryParts.gql';
import UPDATE_ROOM_ENTRY_MUTATION from 'gql/mutations/rooms/updateRoomEntry.gql';

import ContentBlockForm from '@/components/content-block-form/ContentBlockForm';
import { ROOMS_FEATURE_SET } from '@/consts/features.consts';
import { ROOM_PAGE } from '@/router/room.names';

  export default defineComponent( {
    props: {
      slug: {
        type: String,
        required: true
      },
      entrySlug: {
        type: String,
        required: true
      }
    },
  },

  components: {
    ContentBlockForm,
  },

  data() {
    return {
      features: ROOMS_FEATURE_SET,
      roomEntry: {
        title: '',
        contents: [],
      },
    };
  },

  apollo: {
    roomEntry: {
      query: ROOM_ENTRY_QUERY,
      variables() {
        return {
          slug: this.entrySlug,
        };
      },
    },
  },

  methods: {
    goBack() {
      this.$router.push({
        name: ROOM_PAGE,
        params: {
          slug: this.slug,
        },
      });
    },
    save({ title, contents }) {
      const entry = {
        slug: this.roomEntry.slug,
        title,
        contents,
      };
      this.$apollo
        .mutate({
          mutation: UPDATE_ROOM_ENTRY_MUTATION,
          variables: {
            input: {
              roomEntry: entry,
            },
          },
          update: (
            store,
            {
              data: {
                updateRoomEntry: { roomEntry },
              },
            }
          ) => {
            try {
              const fragment = ROOM_ENTRY_FRAGMENT;
              const id = store.identify(roomEntry);
              const cachedEntry = store.readQuery({ fragment, id });
              const data = Object.assign({}, cachedEntry, roomEntry);
              store.writeFragment({
                id,
                fragment,
                data,
              });
            } catch (e) {
              // Query did not exist in the cache, and apollo throws a generic Error. Do nothing
            }
          },
        })
        .then(() => {
          this.goBack();
        });
    },
  },
});
</script>

<style scoped lang="scss">
@import '~styles/helpers';
</style>
