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

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

@Component({
  providers: [CHECK_SELECT_VALUE_ACCESSOR],
  selector: 'cg-check-select',
  template: `

<div class="row">
  <div  *ngFor="let control of form?.controls; let i=index" class="col-3">
    <div  class="form-check form-check-inline">
      <input type="checkbox" [formControl]="getControl(i)"  id="id-cg-check-select-{{i}}" />
      <label for="id-cg-check-select-{{i}}">
        {{_items[i][bindLabel]}}
      </label>
    </div>
  </div>
</div>
  `,
  styles: [
  `
  .form-check{
    white-space:nowrap;
    text-overflow:ellipsis;
  }
  `

  ]
})
export class CheckSelectComponent implements ControlValueAccessor {
  @Input() bindLabel = 'label';
  @Input() bindValue = 'value';

  @Input() set items(val: any) {
    this._items = val;
    this.update();
  }

  onChange;
  onTouched;
  _items: any;
  selectedItems: any;
  form: FormArray;


  constructor(private fb: FormBuilder) { }

  writeValue(obj: any): void {
    console.log('writeValue', obj);
    this.selectedItems = obj;
    this.update();
  }

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

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

  setDisabledState?(isDisabled: boolean): void {
  }

  getControl(index: number) {
    return this.form.controls[index] as FormControl;
  }


  update() {
    if (!this._items) return;
    console.log('selectedItems:', this.selectedItems);
    let controls = this._items.map(item => {
      let value = item[this.bindValue];
      let selected = this.selectedItems != null && this.selectedItems.indexOf(value) >= 0;
      console.log(value, 'selected?', selected)
      return this.fb.control(selected);
    })
    this.form = this.fb.array(controls);
    this.form.valueChanges.subscribe(change => {
      let selected = [];
      for (var i = 0; i < this._items.length; i++) {
        if (change[i]) selected.push(this._items[i][this.bindValue]);
      }
      this.onChange(selected)
    })
  }

}
