<template>
  <room-form
    :room="room"
    @save="addRoom"
  />
</template>

<script>
  import RoomForm from '@/components/rooms/RoomForm';

  import ADD_ROOM_MUTATION from 'gql/mutations/rooms/addRoom.gql';
  import ROOMS_QUERY from '@/graphql/gql/queries/roomsQuery.gql';

  const defaultAppearance = 'blue';

  export default {
    components: {
      RoomForm
    },

    data() {
      return {
        room: {
          appearance: defaultAppearance,
          title: '',
          description: '',
          schoolClass: {}
        }
      };
    },

    methods: {
      addRoom(room) {
        this.$apollo.mutate({
          mutation: ADD_ROOM_MUTATION,
          variables: {
            input: {
              room: room
            }
          },
          update: (store, {data: {addRoom: {room}}}) => {
            try {
              const data = store.readQuery({query: ROOMS_QUERY});
              if (data.rooms) {
                data.rooms.edges.push({
                  node: room,
                  __typename: 'RoomNodeEdge'
                });
                store.writeQuery({query: ROOMS_QUERY, data});
              }
            } catch (e) {
              // Query did not exist in the cache, and apollo throws a generic Error. Do nothing
            }
          }
        }).then(() => {
          this.$router.push('/rooms');
        });
      }
    },
  };
</script>
