<template>
  <div class="picker">
    <div class="form-control" :readonly="readonly" @click="showPopup" ref="popup-anchor">
      <slot name="value"></slot>
      <input class="search" v-model="valueCopy" :placeholder="hasSearch ? 'zoek...' : ''"
        :readonly="!hasSearch"
        @focus="focusSearch"
        @keydown.down.prevent="down"
        @keydown.up.prevent="up"
        @keydown.esc.prevent="valueCopy = ''">
    </div>
    <popup ref="popup" overflow>
      <slot name="options"></slot>
    </popup>
  </div>
</template>

<style lang="scss" scoped>
.picker {
  position: relative;
  user-select: none;
}
.form-control {
  padding: 1px 4px;
}
.search {
  background: transparent;
  border: none;
  outline: none;
  margin: 2px;
  padding: 5px 7px;
  color: #ccc;
  width: 25%;
  &:focus {
    color: inherit;
  }
}
</style>

<script>
import { ValueSyncMixin } from '../shared/value-sync-mixin.js';
import popup from './popup.vue';
import pickerValue from './picker-value.vue';

export default {
  mixins: [ValueSyncMixin],
  props: {
    value: {
      required: true,
      docs: `Ingevoerde zoekwaarde. (optioneel)`,
      demoValue: ''
    },
    readonly: {
      type: Boolean,
      default: false
    },
    onup:  {
      type: Function
    },
    ondown: {
      type: Function
    }
  },
  computed: {
    hasSearch() {
      return this.valueCopy !== null && !this.readonly;
    }
  },
  methods: {
    showPopup() {
      if (!this.readonly) {
        this.$refs.popup.show(this.$refs['popup-anchor']);
      }
    },
    hidePopup() {
      this.$refs.popup.hide();
    },
    focusSearch() {
      this.selectedIndex = -1;
      this.showPopup();
    },
    up() {
      if (this.onup) this.onup();
    },
    down() {
      if (this.ondown) this.ondown();
    }
  },
  components: {
    popup,
    pickerValue
  }
}
</script>
