import { Input, ViewChildren, QueryList, Output, EventEmitter, Component } from '@angular/core';
import { ControlBaseComponent, FilterValue } from '../filter-controls/control-base.component';

@Component({
  template: ''
})
export class DatasourceBaseComponent {
  @ViewChildren('childControl') allChildControls: QueryList<ControlBaseComponent>;
  @Input() dataSourceId: number;
  @Input() filterId: number;
  @Output() valueUpdated = new EventEmitter<number>();

  hasValueCount: number = 0;

  constructor() { }

  getFilterValues(): FilterValue[] {
    const values: FilterValue[] = [];
    this.allChildControls.forEach(childControl => {
      const value: FilterValue = childControl.getFilterValue();
      values.push(value);
    })
    return values;
  }

  setFilterValues(params: FilterValue[]) {
    const childControlsByName: Record<string, ControlBaseComponent> = {};
    this.allChildControls.map(childControl => {
      childControlsByName[childControl.parameterName] = childControl;
      childControl.resetValue();
    })

    params.forEach(param => {
      if (this.dataSourceId === param.dataSourceId) {
        const control = childControlsByName[param.name];
        if (control)
          control.setFilterValue(param);
      }
    })
  }

  get isValid(): boolean {
    let areAllChildControlsValid: boolean = true;
    this.allChildControls.map(childControl => {
      if (!childControl.isValid)
        areAllChildControlsValid = false;
    })
    return areAllChildControlsValid;
  }

  controlValueUpdated() {
    this.hasValueCount = 0;
    this.allChildControls.forEach(childControl => {
      if (childControl.hasValue)
        this.hasValueCount++;
    })
    this.valueUpdated.emit(this.dataSourceId);
  }
}
