<template>
  <div class="itf-field-addon">
    <div class="itf-field-addon__input">
      <slot></slot>
    </div>

    <div v-if="visible" class="itf-field-addon__select">
      <span>{{ label }}<itf-icon v-if="!disabled" name="chevron_down" /></span>
      <select v-if="!disabled" :value="getItemKey(value)" @input="onOptionChanged">
        <template v-for="option in options">
          <option :key="getItemKey(option)" :value="getItemKey(option)" :selected="getItemKey(value) === getItemKey(option)">
            {{ getItemLabel(option) }}
          </option>
        </template>
      </select>
    </div>
  </div>
</template>
<style lang="scss">
.itf-field-addon {
  position: relative;

  &__input input {
    --itf-field-addon--padding-right: 10rem;
    padding-right: var(--itf-field-addon--padding-right);
  }
  &__select {
    z-index: 6;
    position: absolute;
    right: .75rem;
    top: .5rem;
    .is-invalid &, .is-valid & {
      right: 1.75rem;
    }

    select {
      position: absolute;
      top: 0;
      right: 0;
      opacity: 0;
      left: 0;
    }
  }
}
</style>
<script>
import { Component, Emit, Model, Prop, Vue } from 'vue-property-decorator';
import itfIcon from '../icon/Icon';

export default @Component({
  name: 'itfFieldAddonSelect',
  components: {
    itfIcon
  }
})
class itfFieldAddonSelect extends Vue {
  @Model('input', { default: '' }) value;
  @Prop({ type: Boolean, default: false }) disabled;
  @Prop({ type: Boolean, default: true }) visible;
  @Prop({ type: Function, default: (item)  => item.Id}) getItemKey;
  @Prop({ type: Function, default: (item)  => item.Name  }) getItemLabel;
  @Prop({ type: Array, default: () => ([]) }) options;

  onOptionChanged(e) {
    const opt = this.options.find((c) => this.getItemKey(c) === e.target.value);
    this.$emit('input', opt)
  }

  get label() {
    return this.value ? this.getItemLabel(this.value) : '';
  }
}
</script>
