import { Component, OnInit, forwardRef, Input, Output, EventEmitter } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

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

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

  value:boolean;

  //inputs & outputs
  @Input() set checked(val:boolean) {
    this.writeValue(val);
  }

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

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

  constructor() { }

  ngOnInit() {
  }

  writeValue(value:boolean) {
    this.value = value;
  }
  
  registerOnChange(fn:any) {
    this.onChangeCallback = fn;
  }
  
  registerOnTouched(fn:any) {
    this.onTouchedCallback = fn;
  }
  
  onClick(evt) {
    if(this.onChangeCallback) this.onChangeCallback(!this.value);
    evt.target.value = !this.value;
    this.change.emit(evt);
    this.writeValue(!this.value); //posem el contrari
  }

}
