<template>
  <div class="rooms-page">
    <template v-if="filteredRooms.length > 0">
      <room-widget
        v-bind="room"
        :key="room.name"
        class="rooms-page__widget"
        data-cy="room-widget"
        v-for="room in filteredRooms"/>
      <add-room
        class="rooms-page__add-room"
        data-cy="add-room"
        v-if="canAddRoom"/>

    </template>
    <rooms-onboarding
      :is-teacher="me.isTeacher"
      v-else/>
  </div>
</template>

<script>
  import ROOMS_QUERY from '@/graphql/gql/queries/roomsQuery.gql';
  import ME_QUERY from '@/graphql/gql/queries/meQuery.gql';

  import RoomWidget from '@/components/rooms/RoomWidget.vue';
  import AddRoom from '@/components/rooms/AddRoom.vue';
  import RoomsOnboarding from '@/components/rooms/RoomsOnboarding';

  export default {
    components: {
      RoomsOnboarding,
      RoomWidget,
      AddRoom
    },

    data() {
      return {
        rooms: [],
        me: {
          selectedClass: {
            id: ''
          },
          permissions: []
        }
      };
    },

    computed: {
      filteredRooms() {
        return this.rooms.filter(room => this.visibleFor(room, this.currentFilter));
      },
      currentFilter() {
        return this.me.selectedClass.id;
      },
      canAddRoom() {
        return this.me.isTeacher && !this.me.readOnly && !this.me.selectedClass.readOnly;
      }
    },

    methods: {
      visibleFor(room, schoolClass) {
        return !schoolClass || room.schoolClass.id === schoolClass;
      }
    },

    apollo: {
      rooms: {
        query: ROOMS_QUERY,
        update(data) {
          return this.$getRidOfEdges(data).rooms;
        },
        pollInterval: 5000,
      },
      me: {
        query: ME_QUERY,
      },
    },
  };
</script>

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

  .rooms-page {
    display: flex;
    flex-wrap: wrap;
    align-content: start;

    @supports (display: grid) {
      display: grid;
    }

    padding: 50px 15px;
    @include desktop {
      grid-template-columns: repeat(3, 1fr);
      -ms-grid-columns: 1fr 30px 1fr 30px 1fr;
      padding: 50px 45px;
    }
    grid-column-gap: 30px;
    grid-row-gap: 30px;
    grid-auto-rows: 260px;
    max-width: 1440px;
    width: 100%;
    justify-self: center;
    box-sizing: border-box;

    &__add-room {
      visibility: hidden;

      @include desktop {
        visibility: visible;
      }
    }

    &__widget, &__add-room {
      flex: 0 0 30%;
      margin-bottom: $large-spacing;
      margin-right: 1%;

      @supports (display: grid) {
        margin-bottom: inherit;
        margin-right: inherit;
      }
    }
  }
</style>
