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

  export default {
    name: 'TfPopover',
    extends: Popover,
    props: {
      borderColor: {
        type: String,
        default: null,
      },
      closeOnOutsideClick: {
        type: Boolean,
        default: false,
      },
    },
    data: () => ({
      element: null,
    }),
    watch: {
      /**
       * Add/remove event listeners depending on the state of the popper
       *
       * @param {boolean} newVal
       * @param {boolean} oldVal
       */
      showPopper(newVal, oldVal) {
        // store popper DOM element reference
        if (!this.element) {
          this.element = this.$refs.popper;
        }

        if (this.closeOnOutsideClick) {
          if (newVal) {
            document.addEventListener('click', this.outsideClickListener);
          } else {
            this.removeClickListener();
          }
        }

        if (this.borderColor) {
          this.element.style.borderColor = newVal ? this.borderColor : null;
        }

        // Focus on the tool when opening the popover.
        if (!oldVal) {
          this.$nextTick(() => {
            this.element.focus();
          });
        }
      },
    },
    beforeDestroy() {
      this.removeClickListener();
    },
    methods: {
      /**
       * close the popover if someone clicks outside of it
       *
       * @param {event} event
       */
      outsideClickListener(event) {
        if (!this.element.contains(event.target) && this.showPopper) {
          this.removeClickListener();
          this.doClose();
        }
      },
      /**
       * remove the click listener when this is destroyed
       */
      removeClickListener() {
        document.removeEventListener('click', this.outsideClickListener);
      },
    },
  };
</script>
