import Component from '@glimmer/component';
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
import { next } from '@ember/runloop';

export default class SortableGroupAccessibleComponent extends Component {
  @tracked selectedIndex = 0;
  @tracked groupHasFocus = false;

  uniqId = uuid();

  get listElement() { return document.querySelector(`[data-id="${this.uniqId}"]`); }

  @action
  handleFocus() { this.groupHasFocus = true; }

  @action
  handleBlur({ relatedTarget }) {
    if (!this.listElement.contains(relatedTarget)) this.groupHasFocus = false;
  }

  @action
  handleArrowUp() {
    if (this.selectedIndex > 0) {
      this.selectedIndex -= 1;
    }
  }

  @action
  handleArrowDown() {
    if (this.selectedIndex < this.args.models.length - 1) {
      this.selectedIndex += 1;
    }
  }

  @action
  async orderItemUp(index) {
    if (index - 1 < 0) return;

    let item = this.args.models.objectAt(index);
    let prevItem = this.args.models.objectAt(index - 1);

    item.listOrder = index - 1;
    prevItem.listOrder = index;
    this.selectedIndex = index - 1;

    next(this, function() {
      this.listElement.querySelector('[data-action-up]').focus();
    });
  }

  @action
  async orderItemDown(index) {
    if (index + 1 >= this.args.models.length) return;

    let item = this.args.models.objectAt(index);
    let nextItem = this.args.models.objectAt(index + 1);

    item.listOrder = index + 1;
    nextItem.listOrder = index;
    this.selectedIndex = index + 1;

    next(this, function() {
      this.listElement.querySelector('[data-action-down]').focus();
    });
  }

  preventDefault(evt) { evt.preventDefault(); }
}

// Thanks to jed https://gist.github.com/jed/982883
function uuid(a) {
  return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,uuid)
}
