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

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

import NEW_ROOM_ENTRY_MUTATION from 'gql/mutations/rooms/addRoomEntry.gql';
import NEW_MODULE_ROOM_ENTRY_MUTATION from 'gql/mutations/rooms/addModuleRoomEntry.gql';
import ROOM_ENTRIES_QUERY from '@/graphql/gql/queries/roomEntriesQuery.gql';
import me from '@/mixins/me';

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

export default defineComponent({
  props: {
    slug: {
      type: String,
      required: true,
    },
    isModule: {
      type: Boolean,
      default: false,
    },
  },

  mixins: [me],

  components: {
    ContentBlockForm,
  },

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

  methods: {
    goBack() {
      const name = this.isModule ? MODULE_ROOM_PAGE : ROOM_PAGE;
      this.$router.push({
        name,
        params: {
          slug: this.slug,
        },
      });
    },
    save({ title, contents }) {
      const entry = {
        ...{
          title,
          contents,
          roomSlug: this.slug,
        },
        ...(this.isModule && { schoolClass: this.me.selectedClass.id }),
      };
      const mutation = this.isModule ? NEW_MODULE_ROOM_ENTRY_MUTATION : NEW_ROOM_ENTRY_MUTATION;
      this.$apollo
        .mutate({
          mutation,
          variables: {
            input: {
              roomEntry: entry,
            },
          },
          update: (store, { data }) => {
            try {
              const { roomEntry } = this.isModule ? data.addModuleRoomEntry : data.addRoomEntry;
              const query = ROOM_ENTRIES_QUERY;
              const variables = { slug: this.slug };
              const { room } = store.readQuery({ query, variables });
              if (room && room.roomEntries) {
                const newEdge = {
                  node: roomEntry,
                  __typename: 'RoomEntryNodeEdge',
                };
                const edges = [newEdge, ...room.roomEntries.edges];
                const data = {
                  room: {
                    ...room,
                    roomEntries: {
                      ...room.roomEntries,
                      edges,
                    },
                  },
                };
                store.writeQuery({ query, variables, 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>
