import { autoinject, bindable, customElement } from "aurelia-framework";

@customElement("ui-anchor-tab")
@autoinject
export class UIAnchorTab {

  @bindable
  public tabList: Array<AnchorTab>

  @bindable
  public refElement: HTMLElement;
  @bindable
  public useParentHeight: boolean = false;

  @bindable
  public scroll: boolean = true;

  bind() {
    this.tabList.forEach(x => x.isSelected = false);
    let tabVisible = this.tabList.find(x => x.isVisible);
    if (tabVisible != null) {
      tabVisible.isSelected = true;
    }
  }

  attached() {
    this.tabList.forEach(tab => {
      tab.element = this.refElement.ownerDocument.getElementById(tab.id);
    })

    this.refElement.addEventListener('scroll', () => {
      let containerElement = this.containerElement();
      let scrollPercentage = Math.round(containerElement.scrollTop / (containerElement.scrollHeight - containerElement.clientHeight) * 100);

      this.tabList.forEach(tab => {
        if (tab.isVisible) {
          var position = tab.element?.getBoundingClientRect();
          if (position != null && position.top <= Math.round((containerElement.clientHeight / 100) * scrollPercentage)) {
            this.tabList.find(x => x.isSelected).isSelected = false;
            tab.isSelected = true;
          }
        }
      })
    })
  }

  private navigateToAnchor(tab: AnchorTab): void {
    if (this.scroll && this.mustScroll()) {
      document.getElementById(tab.id).scrollIntoView({ behavior: "smooth", block: "start" });
    }
    else {
      this.tabList.find(x => x.isSelected).isSelected = false;
      tab.isSelected = true;
    }
  }

  private mustScroll(): boolean {
    let containerElement = this.containerElement();
    return containerElement.scrollHeight > containerElement.clientHeight;
  }

  private containerElement(): HTMLElement {
    return this.useParentHeight ? this.refElement.parentElement : this.refElement;
  }
}

export interface IAnchorTab {
  id: string;
  name: string;
  isVisible: boolean;
}

export class AnchorTab implements IAnchorTab {
  public id: string;
  public name: string;
  public isSelected: boolean;
  public isVisible: boolean;
  public element: Element;

  constructor(id: string, name: string, isVisible: boolean = true) {
    this.id = id;
    this.name = name;
    this.isVisible = isVisible;
  }
}