import { Component, OnInit, Input, HostListener, Renderer2 } from '@angular/core';
import { NbRenderableContainer, NbMenuItem } from '@nebular/theme';
import { Subscription } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { DropDownOption } from '../../../entity/dropDownOption';
import { DropDownListService } from '../drop-down-list.service';

@Component({
  selector: 'ngx-drop-down-menu',
  templateUrl: './drop-down-menu.component.html',
  styleUrls: ['./drop-down-menu.component.scss']
})
export class DropDownMenuComponent implements NbRenderableContainer {

  // [style.width.px]="clientWidth"

  private _context: menuSetting;
  private _indexSubscription: Subscription;
  clientWidth: number = 0;
  items: DropDownOption[] = [];
  private listener: any;
  constructor(private dropDownListService: DropDownListService,
    private renderer: Renderer2) {
    //super();

  }

  ngOnInit() {
    setTimeout(() => {
      this.listener = this.renderer.listen('window', 'click', (e: Event) => {
        //
        var element = (e.target as HTMLElement);
        if (typeof element.className === 'string' && element.className.indexOf('rbjDropdownMenu') > -1) {
          this.context.focus();
        } else {
          this.context.hide();
          this.listener();
        }
      })
    }, 50);

    this._indexSubscription = this.dropDownListService.focusIndexChange

      .pipe(
        filter(({ tag }) => tag === this._context.tag),
        map(({ focusIndex }) => focusIndex),
      )
      .subscribe(i => {
        this._context.focusIndex = i;
      })
  }
  ngOnDestroy() {
    if (this.listener) { this.listener(); }
    if (this._indexSubscription) {

      this._indexSubscription.unsubscribe();
    }
  }
  public get context(): menuSetting {
    return this._context;
  }
  @Input() public set context(v: menuSetting) {
    if (this._context != v) {
      this._context = v;
      this.clientWidth = document.getElementsByClassName(`div${this._context.tag}`)[0].clientWidth;
      this.items = v.items;
    }
  }

  @HostListener('focus')
  focus() {
    this.context.focus();
  }

  renderContent() {

  }

  choose(item: DropDownOption) {

    if (!item[this.context.propDisabled]) {
      this.dropDownListService.selectItem(this.context.tag, item);
      this.context.hide();
    }
  }

}
export interface menuSetting {
  items: DropDownOption[],
  tag?: string,
  class?: string,
  propDisplay: string,
  propDisabled: string,
  focusIndex: number
  hide: () => {},
  focus: () => {}
}
export interface DropDownBag {
  tag: string,
  item: DropDownOption,
  focusIndex?: number
}

