import { Component, OnInit, forwardRef, AfterContentInit, QueryList, ContentChildren, ElementRef } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { NeuToggleComponent } from './neu-toggle/neu-toggle.component';

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

@Component({
  selector: 'neu-multi-toggle',
  templateUrl: './neu-multi-toggle.component.html',
  styleUrls: ['./neu-multi-toggle.component.css'],
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class NeuMultiToggleComponent implements AfterContentInit {

  private innerValue:any[] = [];
  private _toggles:QueryList<NeuToggleComponent>;
  @ContentChildren(NeuToggleComponent) set toggles(toggles:QueryList<NeuToggleComponent>) {
    if(toggles!=null && toggles!=undefined) {
      this._toggles = toggles;
      
      this.init();
    }
  }
  //placeholders per els callbacks provided per control value accessor
  private onTouchedCallback:() => void;
  private onChangeCallback: (_:any) => void;

  constructor(private eRef:ElementRef) { }

  ngAfterContentInit(): void {

  }

  get value():any[] {
    return this.innerValue;
  }

  set value(v:any[]) {
    if(v && JSON.stringify(v)!==JSON.stringify(v)) {
      this.innerValue = v;
      this.onChangeCallback(v);
    }
  }

  writeValue(value:any[]) {
    if(value && JSON.stringify(value)!==JSON.stringify(this.value)) {
      this.innerValue = value; //no canviar per value
      this.init();
    }
  }

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

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

  private init() {
    this._toggles.forEach((t,i) => {
      const index = this.value.findIndex(val => {
        return JSON.stringify(val)==JSON.stringify(t.value);
      })

      //mirem que no estiguin activats ja
      if(index!=-1) t.active = true;

      //ens suscribim per quan canviin
      t.selected.subscribe(evt => {
        //cada cop hem de buscar-lo
        const idx = this.value.findIndex(val => {
          return JSON.stringify(val)==JSON.stringify(t.value);
        })
        if(evt.active && idx==-1) {
          this.value.push(evt.value);
        }
        else if(!evt.active && idx!=-1) {
          this.value.splice(idx, 1);
        }
      });
    });
  }

}
