import {
  Component,
  Input,
  Output,
  EventEmitter,
  OnChanges,
  OnInit,
  ChangeDetectorRef,
  HostListener,
  Renderer2,
  ElementRef,
  ViewChild
} from '@angular/core';
import { CallbackModel } from '../../models/callback-model';
import { GenericHelper } from '../../helpers/generic-helper';
import { FormGroup, AbstractControl, NgForm } from '@angular/forms';

@Component({
  selector: 'app-form-options',
  templateUrl: './form-options.component.html',
  styleUrls: ['./form-options.component.scss']
})
export class FormOptionsComponent implements OnInit {
  @Output() methodToExecute: EventEmitter<any> = new EventEmitter<any>();

  @Input() populationData: any[];
  @Input() model: any;

  @Input() name: string;
  @Input() placeHolder = 'Select';

  @Input() formGrp: FormGroup;

  @Input() genericErrorMessage?: string = 'Unable to display control';

  @Input() formDir?: NgForm;

  @ViewChild('selector') selector: ElementRef;
  @Input() hideError = false;

  control: AbstractControl;

  error: boolean = false;

  constructor(private ref: ChangeDetectorRef,
    private renderer: Renderer2,
    private el: ElementRef) { }

  ngOnInit() {
    this.setupControl();
    this.onChanges();
  }

  setupControl(): void {
    this.control = this.formGrp.get(this.name);
    // if model passed in is valid in populationData array passed in then set a preselected value
    if (this.model && this.populationData && (this.populationData.indexOf(this.model) !== -1)) {
      this.control.setValue(this.model);
    }

    // if control is required but NgForm isnt passed in!!
    if (this.control.validator && (this.control.validator({} as AbstractControl))
     && (this.control.validator({} as AbstractControl)).required
     && (this.formDir === undefined || this.formDir === null)) {
      this.error = true;
      this.genericErrorMessage = "Error has occured! (NgForm unavailable!)";
    }
  }

  clearControl(): void {
    this.control.setValue(undefined);
  }

  onChanges(): void {
    this.control.valueChanges.subscribe(val => {
      this.methodToExecute.emit(val);
    });
  }


  onFocus(event: KeyboardEvent) {
    const elem = <HTMLSelectElement>event.target
    elem.size = this.populationData.length > 10 ?
      10 : this.populationData.length;
    this.renderer.setStyle(this.selector.nativeElement, 'z-index', "2");
  }

  onBlur(event: KeyboardEvent) {
    const elem = <HTMLSelectElement>event.target
    elem.size = 1;
    this.renderer.setStyle(this.selector.nativeElement, 'z-index', "1");
  }

  onChange(event: KeyboardEvent) {
    const elem = <HTMLSelectElement>event.target
    elem.size = 1;
    elem.blur();
  }

}
