<template>
  <div class="dropdown-menu-container" :class="{ 'show': isOpen, 'full-width': fullWidth }" @click.stop>
    <button type="button" class="nav-link dropdown-toggle" :class="{ disabled, 'hide-arrow': hideArrow }" id="navbarDropdown" @click.prevent="toggleDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" :aria-expanded="isOpen">
      <slot v-if="$slots.label" name="label"></slot>
      <template v-else>
        <span v-if="fullWidth" class="text-truncate d-inline-block dropdown-toggle-text">{{ label }}</span>
        <template v-else>{{ label }}</template>
      </template>
    </button>
    <div class="dropdown-menu" ref="dropdownMenu" :class="{ 'show': isOpen, right }" aria-labelledby="navbarDropdown">
      <div v-on:click="onDropdownItemClick">
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.dropdown-menu-container {
  &.full-width {
    &,
    .dropdown-toggle,
    .dropdown-menu {
      width: 100%;
      text-align: left;
    }

    .dropdown-toggle {
      display: flex;
      align-items: center;

      &-text {
        width: 90%;
      }
    }
  }

  button {
    background: none;
    border: 0;
    cursor: pointer;
  }

  .dropdown-toggle {
    &.hide-arrow {
      &::after {
        display: none;
      }
    }
  }

  .dropdown-menu {
    position: absolute;

    &.right {
      left: auto;
      right: 0;
    }

    ::v-deep button:hover {
      background-color: #f8f9fa;
    }

    ::v-deep .nav-link {
      &.active, &:active {
        background: none;
      }
    }
  }
}
</style>

<script>
import { EventBus, EventBusTypes } from '../tools/event-bus';

export default {
  props: {
    label: {
      type: String,
      required: true,
      docs: `De tekst van de link waarmee je de dropdown opent.`,
      demoValue: 'Dropdown',
    },
    closeOnClick: {
      type: Boolean,
      default: true
    },
    disabled: Boolean,
    fullWidth: Boolean,
    hideArrow: Boolean,
    right: Boolean
  },
  created() {
    document.addEventListener('click', this.onClickOutside, false);
    EventBus.$on(EventBusTypes.CloseDropdowns, this.close);
  },
  beforeDestroy() {
    document.addEventListener('click', this.onClickOutside, false);
    EventBus.$off(EventBusTypes.CloseDropdowns, this.close);
  },
  data() {
    return {
      isOpen: false,
    };
  },
  methods: {
    async toggleDropdown() {
      if (!this.isOpen) {
        EventBus.$emit(EventBusTypes.CloseDropdowns);
      }

      this.isOpen = !this.isOpen;
    },
    onDropdownItemClick() {
      if (this.closeOnClick) {
        this.toggleDropdown();
      }
    },
    close() {
      this.isOpen = false;
    },
    onClickOutside() {
      if (this.isOpen) {
        this.toggleDropdown();
      }
    }
  },
};
</script>
