<template>
  <more-actions data-cy="room-actions">
    <popover-link
      icon="pen-icon"
      text="Bearbeiten"
      @link-action="editRoom()"/>
    <popover-link
      icon="eye-icon"
      data-cy="change-visibility"
      text="Sichtbarkeit anpassen"
      @link-action="changeVisibility()"/>
    <popover-link
      icon="trash-icon"
      text="Löschen"
      data-cy="delete-room"
      @link-action="deleteRoom()"/>
  </more-actions>
</template>

<script>

  import DELETE_ROOM_MUTATION from 'gql/mutations/rooms/deleteRoom.gql';
  import UPDATE_ROOM_VISIBILITY_MUTATION from 'gql/mutations/rooms/updateRoomVisibility.gql';

  import ROOMS_QUERY from '@/graphql/gql/queries/roomsQuery.gql';
  import PopoverLink from '@/components/ui/PopoverLink';
  import {ROOMS_PAGE} from '@/router/room.names';
  import MoreActions from '@/components/rooms/MoreActions';

  export default {
    props: {
      id: {
        type: String,
        default: '',
      },
      restricted: {
        type: Boolean,
        default: false,
      },
    },

    components: {
      MoreActions,
      PopoverLink,

    },

    methods: {
      deleteRoom() {
        this.$apollo.mutate({
          mutation: DELETE_ROOM_MUTATION,
          variables: {
            input: {
              id: this.id,
            },
          },
          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 === this.id), 1);
                store.writeQuery({query: ROOMS_QUERY, data});
              }
            }
            this.$router.push({
              name: ROOMS_PAGE,
            });
          },
        });
      },
      editRoom() {
        this.$router.push({name: 'edit-room', params: {id: this.id}});
      },
      changeVisibility() {
        this.showMenu = false;
        this.$modal.open('change-visibility', {restricted: this.restricted})
          .then((restricted) => {
            this.$apollo.mutate({
              mutation: UPDATE_ROOM_VISIBILITY_MUTATION,
              variables: {
                input: {
                  id: this.id,
                  restricted,
                },
              },
            });
          })
          .catch(() => {

          });
      },
    },
  };
</script>

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

  $height: 30px;

  .room-actions {
    height: $height;

    &__more-link {
      cursor: pointer;
      height: $height;
    }

    &__popover {
      display: flex;
      width: max-content;
    }
  }
</style>
