import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy, OnInit, ChangeDetectorRef, ViewRef } from '@angular/core';

@Component({
  selector: 'app-select',
  templateUrl: './select.component.html',
  styleUrls: ['./select.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SelectComponent implements OnInit {
  @Input() options: string[] | number[];
  @Input() selected: string | number;
  @Input() label: string | number;
  @Input() showrequired: boolean;
  @Input() error: boolean;
  @Input() errorMessage: string;
  @Input() displayErrorUnder: boolean;
  @Input() value: string = null;
  @Input() maxheight = '';
  @Input() scroll = false;
  @Output() valueChanges: EventEmitter<string | number> = new EventEmitter();
  isOpen = false;
  dirty: boolean;
  timer: any;
  @Input() set isDirty(value: boolean) {
    clearInterval(this.timer);
    this.timer = setTimeout(() => {
      if (this.value === this.label) {
        this.dirty = false;
      } else {
        this.dirty = value;
      }
      this.detectChanges();
    }, 500);
  }

  get hasscroll() {
    return scroll ? 'scroll' : '';
  }

  constructor(private cdRef: ChangeDetectorRef) {}

  ngOnInit() {
    this.dirty = this.value ? true : false;
    if (this.dirty) {
      this.selected = this.value;
    }
  }

  onChange(option: string | number) {
    this.dirty = option !== this.label;
    this.selected = this.dirty ? option : this.label;
    this.valueChanges.emit(option);
    this.toggleDropdown();
  }

  public change(option: string | number) {
    this.dirty = option !== this.label;
    this.selected = this.dirty ? option : this.label;
  }

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

  public clear(label: string) {
    this.dirty = false;
    this.value = null;
    this.selected = label;
  }

  detectChanges() {
    setTimeout(() => {
      if (this.cdRef !== null && this.cdRef !== undefined && !(this.cdRef as ViewRef).destroyed) {
        this.cdRef.detectChanges();
      }
    }, 0);
  }
}
