import { Component, OnInit, forwardRef, ContentChildren, QueryList, AfterContentInit, Input } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { NeuRadioButtonComponent } from '../neu-radio-button/neu-radio-button.component';

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR:any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => NeuRadioGroupComponent),
  multi: true
}

@Component({
  selector: 'neu-radio-group',
  templateUrl: './neu-radio-group.component.html',
  styleUrls: ['./neu-radio-group.component.css'],
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class NeuRadioGroupComponent implements ControlValueAccessor, AfterContentInit {

  private innerValue:any;
  @ContentChildren(NeuRadioButtonComponent) radios:QueryList<NeuRadioButtonComponent>;

  get value():any { return this.innerValue; }
  @Input() set value(v:any) { if(v!==this.innerValue) { this.innerValue = v; if(this.onChangeCallback) this.onChangeCallback(v); } }

  //placeholders per els callbacks provided per control value accessor
  private onTouchedCallback:() => void;
  private onChangeCallback: (_:any) => void;

  constructor() { }

  ngAfterContentInit() {
    const self = this;
    this.radios.forEach(radio => {
      radio.selected.subscribe(evt => {
        this.writeValue(evt.value);
      });
    })
  }

  writeValue(value:any) {
    if(value!==this.innerValue && this.radios != null) {
      this.radios.forEach(r => {
        if(r.value == value) {
          r.active = true;
        }
        else {
          r.active = false;
        }
        this.innerValue = value;
        if(this.onChangeCallback) this.onChangeCallback(value);
      });
    }
  }

  registerOnChange(fn:any) {
    this.onChangeCallback = fn;
  }

  registerOnTouched(fn:any) {
    this.onTouchedCallback = fn;
  }

}
