<template>
  <v-tooltip
    :value="show"
    :top="top"
    :bottom="bottom"
    :right="right"
    :left="leftOrDefault"
    :open-on-hover="false"
    :open-on-focus="false"
    :open-on-click="false"
    max-width="360px"
  >
    <template #activator="{}">
      <v-icon
        @click="onIconClicked"
        icon
        class="ml-3"
        size="18px"
        ref="iconRef"
      >
        {{ icon }}
      </v-icon>
    </template>

    <div ref="slotDiv" class="tooltip" v-click-out="onClickOutside">
      <slot></slot>
    </div>
  </v-tooltip>
</template>

<script lang="ts">
import { defineComponent, ref, Ref } from '@nuxtjs/composition-api'


export default defineComponent({
  props: {
    left: {
      type: Boolean,
      required: false,
      default: false
    },
    right: {
      type: Boolean,
      required: false,
      default: false
    },
    top: {
      type: Boolean,
      required: false,
      default: false
    },
    bottom: {
      type: Boolean,
      required: false,
      default: false
    },
    icon: {
      type: String,
      required: false,
      default: 'mdi-help-circle'
    }
  },
  setup(props, $refs) {
    const show: Ref<Boolean> = ref(false)

    // template reference to the icon object
    const iconRef = ref(null)

    // Because left is the default direction, this property will return true if
    // left has been defined in the props, or if no other direction has been given
    const leftOrDefault: Ref<Boolean> = ref(props.left || (!props.right && !props.bottom && !props.top))

    const onIconClicked = (e: any) => {
      show.value = !show.value
      e.stopPropagation()
    }

    const onClickOutside = (e: any) => {
      if (show.value) {
        if (e.target === (iconRef.value as any).$el)     {
          return
        }
        show.value = false
      }
    }

    return {
      iconRef,
      leftOrDefault,
      show,
      onIconClicked,
      onClickOutside
    }
  }
})
</script>

<style>
.v-icon {
  cursor: pointer;
  height: 18px;
  width: 18px;
}
.v-tooltip__content {
  pointer-events: all !important;
}
</style>
