<template>
  <div class="room-actions">
    <a
      class="room-actions__more-link"
      @click="toggleMenu">
      <ellipses/>
    </a>
    <widget-popover
      class="room-actions__popover"
      v-if="showMenu"
      @hide-me="showMenu = false">
      <li class="popover-links__link"><a @click="deleteRoom()">Raum löschen</a></li>
      <li class="popover-links__link"><a @click="editRoom()">Raum bearbeiten</a></li>
    </widget-popover>
  </div>
</template>

<script>
  import Ellipses from '@/components/icons/Ellipses.vue';
  import WidgetPopover from '@/components/WidgetPopover';

  import DELETE_ROOM_MUTATION from '@/graphql/gql/mutations/deleteRoom.gql';
  import ROOMS_QUERY from '@/graphql/gql/queries/roomsQuery.gql';

  export default {
    props: ['id'],

    components: {
      Ellipses,
      WidgetPopover
    },

    data() {
      return {
        showMenu: false
      };
    },

    methods: {
      toggleMenu: function () {
        this.showMenu = !this.showMenu;
      },
      deleteRoom() {
        const theId = this.id;
        this.$apollo.mutate({
          mutation: DELETE_ROOM_MUTATION,
          variables: {
            input: {
              id: theId
            }
          },
          update(store, {data: {deleteRoom: {success}}}) {
            if (success) {
              const data = store.readQuery({query: ROOMS_QUERY});
              if (data) {
                data.rooms.edges.splice(data.rooms.edges.findIndex(edge => edge.node.id === theId), 1);
                store.writeQuery({query: ROOMS_QUERY, data});
              }
            }
          }
        });
      },
      editRoom() {
        this.$router.push({name: 'edit-room', params: {id: this.id}});
      }
    }
  };
</script>

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

  .room-actions {
    &__more-link {
      cursor: pointer;
    }

    &__popover {
      @include popover-defaults();
    }

    svg {
      width: 30px;
      fill: $color-charcoal-dark;
      margin-right: 15px;
    }
  }
</style>
