<template>
  <div class="room">
    <div class="room__back">
      <back-link
        type="room"
        title="Zurück zur Übersicht"/>
    </div>
    <div class="room__context-menu">
      <room-actions
        :id="room.id"
        :restricted="room.restricted"
        class="room__actions"
        v-if="canEdit"/>
    </div>
    <div class="room__header">
      <h1
        class="room__title"
        data-cy="room-title">{{ room.title }}</h1>
      <p class="room__intro">
        {{ room.description }}
      </p>
      <div class="room__meta">
        <room-visibility-widget
          :restricted="room.restricted"
          data-cy="room-visibility-status"/>
        <room-group-widget v-bind="room.schoolClass"/>
        <entry-count-widget :entry-count="roomEntryCount"/>
      </div>
    </div>
    <div class="room__content">
      <add-room-entry-button
        :parent="room"
        v-if="room.id && !isReadOnly">
        <!--
        the v-if is there for the case where the room hasn't loaded yet, but there is already an attempt to create
        a new room entry. mainly happens during cypress testing, but could also happen on a very slow connection
        -->
      </add-room-entry-button>
      <room-entry
        v-bind="entry"
        :key="entry.id"
        v-for="entry in room.roomEntries"/>
    </div>
  </div>
</template>

<script>
  import ROOM_ENTRIES_QUERY from '@/graphql/gql/queries/roomEntriesQuery.gql';
  import room from '@/mixins/room';
  import me from '@/mixins/me';
  import BackLink from '@/components/BackLink';
  import RoomVisibilityWidget from '@/components/rooms/RoomVisibilityWidget';
  import {ROOMS_PAGE} from '@/router/room.names';

  export default {
    props: ['slug'],
    mixins: [room, me],
    components: {RoomVisibilityWidget, BackLink},

    computed: {
      canEdit() {
        return this.me.isTeacher && !this.isReadOnly;
      },
      isReadOnly() {
        return this.me.readOnly || this.me.selectedClass.readOnly;
      },
    },

    mounted() {
      this.$watch(
        'me.selectedClass.id',
        (newValue, _) => {
          if (this.room.schoolClass.id !== newValue) {
            this.$router.push({
              name: ROOMS_PAGE,
            });
          }
        },
      );
    },

    apollo: {
      room: {
        query: ROOM_ENTRIES_QUERY,
        variables() {
          return {
            slug: this.slug,
          };
        },
        update({room}) {
          this.$store.dispatch('setSpecialContainerClass', room.appearance);
          return this.$getRidOfEdges(room);
        },
        pollInterval: 5000,
      },
    },
  };
</script>

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