<template>
  <div class="class-selection" v-if="isTeacher">
    <div class="class-selection__selected-class selected-class" @click="showPopover = !showPopover">
      <p class="selected-class__text">Klasse: {{currentClassSelection.name}}</p>
    </div>
      <widget-popover v-if="showPopover"
                      @hide-me="showPopover = false"
                      :mobile="mobile"
                      class="class-selection__popover">
        <li class="popover-links__link popover-links__link--large" v-for="schoolClass in schoolClasses"
          :key="schoolClass.id"
          :label="schoolClass.name"
          :item="schoolClass"
          @click="updateFilter(schoolClass)">
          {{schoolClass.name}}
        </li>
    </widget-popover>
  </div>
</template>

<script>
  import WidgetPopover from '@/components/WidgetPopover';
  import ME_QUERY from '@/graphql/gql/meQuery.gql';
  import UPDATE_USER_SETTING from '@/graphql/gql/mutations/updateUserSetting.gql';

  export default {
    components: {
      WidgetPopover
    },

    props: {
      mobile: {
        type: Boolean,
        default: false
      }
    },

    apollo: {
      me: {
        query: ME_QUERY
      }
    },

    data() {
      return {
        me: {
          selectedClass: {
            id: ''
          },
          permissions: []
        },
        showPopover: false
      }
    },

    methods: {
      updateFilter(selectedClass) {
        this.$apollo.mutate({
          mutation: UPDATE_USER_SETTING,
          variables: {
            input: {
              id: selectedClass.id
            }
          },
          update(store, data) {
            let meData = store.readQuery({query: ME_QUERY});
            meData.me.selectedClass = selectedClass
            store.writeQuery({query: ME_QUERY, data: meData});
          }
        }).catch((error) => {
          console.log('fail', error)
        });
        this.showPopover = false;
      }
    },

    computed: {
      currentClassSelection() {
        let currentClass = this.schoolClasses.find(schoolClass => {
          return schoolClass.id === this.me.selectedClass.id
        })
        return currentClass || this.schoolClasses[0];
      },
      schoolClasses() {
        return this.$getRidOfEdges(this.me.schoolClasses);
      },
      isTeacher() {
        return this.me.permissions.includes('users.can_manage_school_class_content');
      }
    },

  }
</script>

<style scoped lang="scss">
  @import "@/styles/_variables.scss";
  @import "@/styles/_mixins.scss";

  .class-selection {

    position: relative;
    cursor: pointer;
    margin-right: $large-spacing;

    &__popover {
      white-space: nowrap;
      top: 40px;
    }
  }

  .selected-class {
    &__text {
      line-height: $large-spacing;
      @include regular-text;
      color: $color-silver-dark;
      }
    }

  .popover-links__link {
    cursor: pointer;
  }

</style>
