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

export const CHECKBOX_CONTROL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => CheckBoxComponent),
  multi: true
};

@Component({
  selector: 'ui-kit-checkbox',
  templateUrl: './checkbox.component.html',
  styleUrls: ['../../../styles/css/checkbox.css'],
  providers: [CHECKBOX_CONTROL_VALUE_ACCESSOR]
})
export class CheckBoxComponent {
  @Input() class;
  private internalValue: any;

  private onTouchedCallback: () => void = () => { };
  private onChangeCallback: (_: any) => void = () => { };

  get value(): any {
    return this.internalValue;
  };

  set value(value: any) {
    if (value !== this.internalValue) {
      this.internalValue = value;
      this.onChangeCallback(value);
    }
  }

  ngOnInit() {
    this.class = `ui-kit-checkbox-container ${this.class}`;
  }

  toggle() {
    this.value = !this.value;
  }

  writeValue(value: any) {
    if (value !== this.internalValue) {
      this.internalValue = value;
    }
  }

  onBlur() {
    this.onTouchedCallback();
  }

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

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