<template>
  <div class="pui-select has-action treeselect"
    :class="[
      size,
      state,
      {
        'has-icon': icon,
        'has-label': label,
        'has-hint': hint,
        'filled': isFilled,
        'focused': isFocused,
        'auto-height': autoHeight,
        'is-required': required
      }
    ]"
    :disabled="disabled"
  >
    <p-icon v-if="icon" :size="size" :icon="icon" />
    <span class="label" v-if="label">{{ label }}</span>
    <treeselect
      class="pui-treeselect"
      @open="onOpen"
      @close="onClose"
      @input="onInput"
      v-bind="$attrs"
      placeholder=""
      ref="treeselect"
      v-model="computedValue"
      :disabled="disabled"
    />
    <p-tooltip 
      class="hint" 
      v-if="hint"
      :label="hint"
      position="is-top"
      :width="tooltipWidth"
      :is-multiline="hint.length > 80"
      trigger="hover"
    >
      <i class="mdi mdi-information-outline"></i>
    </p-tooltip>
    <div class="chevron"><i class="mdi mdi-chevron-down"></i></div>
    <div class="action-trigger" v-if="isFilled && !disabled" @click="clear">
      <i class="mdi mdi-close"></i>
    </div>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'

const isValueEmpty = (value) => {
  return (typeof value !== "object" && typeof value !== "undefined") ||
         (typeof value === "object" && typeof value.length !== "undefined" && value.length > 0)
}

export default {
  name: 'PTreeSelect',
  props: {
    size: String,
    state: String,
    icon: String,
    label: String,
    autoHeight: Boolean,
    required: Boolean,
    disabled: Boolean,
    value: null,
    hint: String
  },
  components: {Treeselect},
  data() {
    return {
      isFocused: false,
      isFilled: false
    }
  },
  methods: {
    onOpen(instanceId) {
      this.isFocused = true
      this.$emit('open', {instanceId})
    },
    onClose(value, instanceId) {
      this.isFocused = false
      this.$emit('close', {value, instanceId})
    },
    onInput(value, instanceId) {
      if (isValueEmpty(value)) {
        this.isFilled = true
      } else {
        this.isFilled = false
      }

      this.$emit('close', {value, instanceId})
    },
    clear() {
      this.$refs.treeselect.clear();
      this.$emit('clear')
    }
  },
  mounted() {
    if (isValueEmpty(this.value)) {
      this.isFilled = true
    } else {
      this.isFilled = false
    }
  },
  computed: {
    computedValue: {
      get() {
        return this.value;
      },
      set(value) {
        this.$emit("input", value);
      },
    },
    tooltipWidth() {
      return (typeof this.hint === 'string' && this.hint.length > 80) ? 200 : 'auto'
    }
  }
}
</script>