import {
  Component,
  Input,
  Output,
  EventEmitter,
  ChangeDetectionStrategy,
  ViewChild,
  ElementRef,
  OnInit,
  OnDestroy,
  HostListener,
  ChangeDetectorRef,
} from '@angular/core';

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DropdownComponent {
  @Input() options: any;
  @Input() selected: any;
  @Input() showFull = false;
  @Input() onlySelectedFull = false;
  @Input() isKeyValue = false;
  @Input() rightAligned = false;
  @Input() leftAligned = false;
  @Input() scrollable = false;
  @Input() floating = false;
  @Input() index: number;
  @Input() load = false;
  @Input() loading;
  @Input() showClosingArrow = false;
  @Input() optionsUnder = false;
  @Input() boldSelected = false;
  @Input() boldDdSelectedValue = false;
  @Input() mode = 'customer';
  @Input() fitContent = false;
  @Output() valueChanges: EventEmitter<any> = new EventEmitter();
  isOpen = false;
  absolute = false;
  top = 152 * this.index;
  @ViewChild('slectedItem') element: ElementRef;
  @ViewChild('container') container: ElementRef;

  constructor(private cdrf: ChangeDetectorRef) {}

  onChange(option: any, event: any) {
    if (this.showClosingArrow && (event.target.id === 'close-kv' || event.target.id === 'close-dd')) {
      this.toggleDropdown();
    } else {
      this.toggleDropdown();
      this.valueChanges.emit(option);
    }
  }

  toggleDropdown() {
    this.isOpen = !this.isOpen;
  }

  public closeDropdown() {
    this.isOpen = false;
    this.cdrf.detectChanges();
  }

  public setTop(scrollTop: number) {
    this.top = -scrollTop + 152 * this.index - this.index * 15;
    this.cdrf.detectChanges();
  }

  @HostListener('window:scroll', ['$event'])
  scrollHandler(event) {
    if (this.absolute === false) {
      this.absolute = true;
    }
  }
}
