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

@Component({
  selector: 'app-input',
  templateUrl: './input.component.html',
  styleUrls: ['./input.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class InputComponent implements OnInit, AfterViewInit {
  @ViewChild('input') input: ElementRef;
  @Input() type: string;
  @Input() id: string;
  @Input() value: string = null;
  @Input() required: boolean;
  @Input() label: string;
  @Input() error: boolean;
  @Input() errorMessage: string;
  @Input() displayErrorUnder: boolean;
  @Input() focus: boolean;
  @Input() showrequired: boolean;
  @Input() trim = false;
  @Input() dirty: boolean;
  timer: any;
  @Input() set isDirty(value: boolean) {
    clearInterval(this.timer);
    this.timer = setTimeout(() => {
      this.dirty = value;
      this.detectChanges();
    }, 500);
  }
  @Output() valueChanges: EventEmitter<string> = new EventEmitter();

  constructor(private cdRef: ChangeDetectorRef) {}

  ngOnInit() {
    this.dirty = this.value && this.value.length > 0 ? true : false;
  }

  ngAfterViewInit() {
    if (this.focus) {
      this.input.nativeElement.focus();
    }
  }

  onChange(value: string) {
    if (value) {
      this.dirty = true;
    } else {
      this.dirty = false;
    }
    if (this.trim) {
      value = value.trim();
    }
    this.valueChanges.emit(value);
  }

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