import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { CallbackModel } from '../../models/callback-model';
import { GenericHelper } from '../../helpers/generic-helper';
import { dataUrl } from 'angular-file/file-upload/fileTools';
import { FormGroup, AbstractControl, NgForm } from '@angular/forms';

@Component({
  selector: 'app-form-radio',
  templateUrl: './form-radio.component.html',
  styleUrls: ['./form-radio.component.scss']
})
export class FormRadioComponent implements OnInit {
  @Input() data: any[];

  @Input() model: any;
  
  @Input() formGrp: FormGroup;

  @Output() methodToExecute: EventEmitter<any> = new EventEmitter<any>();

  @Input() name: string;
  control: AbstractControl;
  
  @Input() formDir?: NgForm;

  error: boolean;
  constructor() {}

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

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

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


  onRadioChange(obj: any) {
    this.methodToExecute.emit(obj);
  }
}
