<script>
  import { Submenu } from 'element-ui';

  export default {
    name: 'TfSubmenu',
    extends: Submenu,
    props: {
      closeOnOutsideClick: {
        type: Boolean,
        default: false,
      },
      popperClassName: {
        type: String,
        default: 'tf-hamburger-popper',
      },
    },
    data: () => ({
      element: null,
    }),
    watch: {
      /**
       * Watch when the menu opens/closes
       *
       * @param {boolean} newVal
       */
      opened(newVal) {
        if (newVal && this.closeOnOutsideClick) {
          const [element] = document.getElementsByClassName(this.popperClassName);
          this.element = element;
          // Add a little delay for this
          // There's an issue on carrier that is emitting on initial trigger
          setTimeout(() => {
            document.addEventListener('click', this.outsideClickListener);
          }, 10);
        } else {
          this.removeClickListener();
        }
      },
    },
    beforeDestroy() {
      this.removeClickListener();
    },
    methods: {
      /**
       * If a user clicks outside the menu we want to hide it
       *
       * @param {event} event
       */
      outsideClickListener(event) {
        if (this.opened && !this.element.contains(event.target)) {
          this.removeClickListener();
          this.$emit('hide');
        }
      },
      /**
       * We want to remove our listener when the component is destroyed
       */
      removeClickListener() {
        document.removeEventListener('click', this.outsideClickListener);
      },
    },
  };
</script>
