import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { CallbackModel } from '../../models/callback-model';
import { GenericHelper } from '../../helpers/generic-helper';
import { IValidationOptions } from '../../interfaces/validation-options.interface';
import {
  FormGroup,
  FormControl,
  Validators,
  AbstractControl,
  ValidationErrors,
  NgForm
} from '@angular/forms';

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

  @Input() name: string;
  @Input() placeHolder: any;
  @Input() model: any;

  @Input() formGrp: FormGroup;

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

  @Input() formDir?: NgForm;
  @Input() hideError = false;

  error: boolean;

  constructor() { }

  control: AbstractControl;

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

  setupControl(): void {
    this.control = this.formGrp.get(this.name);
    if (this.model) {
      this.control.setValue(this.model);
    }
  }

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