<template>
  <div class="component component-dropdown" :class="{ disabled: !!disabled, 'open-up': !!openUp }" v-on-clickaway="() => showOptions = false" ref="dropdown">
    <div class="value" :class="{ 'options-open' : !!showOptions }" @click="showOptions = !showOptions">
      <span class="text" :class="{ placeholder : !selectedValue }">{{ selectedText }}</span>
      <span class="icon"><i class="fas fa-caret-down"></i></span>
    </div>
    <ul class="options" v-show="!!showOptions">
      <li :class="{ selected : selectedValue === item }" @click="select(item)" v-for="item in options">
        {{ (!!optionLabel) ? item[optionLabel] : item }}
      </li>
    </ul>
  </div>
</template>

<script>
  import { mixin as clickaway } from 'vue-clickaway2';
  
  export default {
    mixins: [ clickaway ],
    props: [ "value", "options", "optionLabel", "placeholder", "disabled" ],
    data() {
      return {
        showOptions: false,
        openUp: false
      };
    },
    mounted() {
      const elementRect = this.$refs.dropdown.getBoundingClientRect();
      const spaceBelow = window.innerHeight - elementRect.bottom;
      
      // TODO: Come up with a good number to use here
      if (spaceBelow < 50) {
        this.openUp = true;
      }
    },
    computed: {
      selectedValue: {
        get() {
          return this.value;
        },
        set() {
          // nothing?
        }
      },
      selectedText: function() {
        const component = this;
        
        if (!!this.options && !!this.selectedValue) {
          const selected = this.options.find( function(item) {
            return item === component.selectedValue;
          });
          
          if (!!selected) {
            if (!!this.optionLabel) {
              return selected[this.optionLabel];
            }
            else {
              return selected;
            }
          }
        }
        
        return this.placeholder || "";
      }
    },
    methods: {
      select(item) {
        this.showOptions = false;
        if (!!this.optionValue && !!this.optionLabel) {
          this.selectedValue = item[this.optionLabel];
        }
        else {
          this.selectedValue = item;
        }
        this.$emit('input', item);
        this.$emit('change');
      }
    }
  }
</script>
