<template>
  <div class="label-selector">
    <input ref="input" type="text"
           v-model="search" placeholder="Search...">

    <div v-if="results.length > 0" class="labels">
      <div v-for="(label, index) in results" v-bind:key="label.identifier"
           class="label selectable"
           :class="{selected: index === selectedIndex}"
           @click="select(label)">
        <div class="hierarchy" v-if="label.hierarchy_level">
          {{ label.hierarchy_level }}
        </div>
        <div class="name">
          {{ label.name }}
        </div>
      </div>
    </div>

    <div v-else class="labels">
      <div class="label">
        No results found...
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "label-selector",
  props: ['labels'],
  mounted: function () {
    // register events to prevent global hotkeys while typing
    window.addEventListener('keypress', this.keypress, true);
    window.addEventListener('keydown', this.keypress, true);
    window.addEventListener('wheel', this.keypress, true);

    // focus text input
    this.$refs.input.focus();
  },
  destroyed: function () {
    window.removeEventListener('keypress', this.keypress, true);
    window.removeEventListener('keydown', this.keypress, true);
    window.removeEventListener('wheel', this.keypress, true);
  },
  data: function () {
    return {
      search: '',
      selectedIndex: 0
    }
  },
  computed: {
    sortedLabels: function () {
      return [...this.labels].sort((a, b) => {
        if (a.hierarchy_level !== b.hierarchy_level) {
          if (a.hierarchy_level === null)
            return -1;
          if (b.hierarchy_level === null)
            return +1;
          if (a.hierarchy_level < b.hierarchy_level)
            return -1;
          else
            return +1;
        }

        if (a.name < b.name)
          return -1;
        else
          return +1;
      });
    },
    results: function () {
      const search = this.search.toLowerCase();

      return [{
        identifier: null,
        name: 'None'
      }, ...this.sortedLabels]
          .filter(l => !this.search || !l.identifier || l.name.toLowerCase().includes(search));
    }
  },
  methods: {
    keypress: function (event) {
      event.stopPropagation();

      switch (event.key) {
        case 'ArrowDown':
          this.selectedIndex += 1;
          if (this.selectedIndex >= this.results.length)
            this.selectedIndex = this.results.length - 1;
          break;

        case 'ArrowUp':
          this.selectedIndex -= 1;
          if (this.selectedIndex < 0)
            this.selectedIndex = 0;
          break;

        case 'Enter':
          this.select(this.results[this.selectedIndex]);
          break;

        case 'Escape':
          this.closeDelayed();
          break;

        default:
          this.selectedIndex = Math.min(1, this.results.length - 1);
          break;
      }
    },
    select: function (label) {
      this.$emit('label', label);
      this.closeDelayed();
    },
    closeDelayed: function () {
      setTimeout(() => this.$emit('close', true), 100);
    }
  }
}
</script>

<style scoped>
.label-selector {
  display: flex;
  flex-direction: column;

  padding: 1rem;
  background-color: rgba(0, 0, 0, 0.65);
  color: whitesmoke;
}

input {
  margin-bottom: 0.5rem;
  padding: 0.3rem;
}

.labels {
  flex-grow: 1;
  overflow: auto;
}

.label {
  padding: 0.25rem 0;
}

.label:not(:last-child) {
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.label.selectable:hover,
.label.selected {
  background-color: var(--primary);
  padding: 0.25rem 0.5rem;
}

.hierarchy {
  font-size: 77%;
  opacity: 0.8;
}
</style>