/*
 * Copyright (C) 2023 Robert Bosch GmbH Copyright (C) 2023 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { AfterContentInit, Component, ContentChildren, EventEmitter, Input, Output, QueryList } from '@angular/core';
import { BciFilterFieldComponent } from '../bci-filter-field/bci-filter-field.component';
import { BciFilterService } from '../service/bci-filter.service';
import { FormControl, FormGroup } from '@angular/forms';

/**
 * Component is used as a wrapper for the multiple fields acting as a section
 */
@Component({
  selector: 'bci-filter-section',
  templateUrl: './bci-filter-section.component.html',
  styleUrls: ['./bci-filter-section.component.scss'],
})
export class BciFilterSectionComponent implements AfterContentInit {

  // Used for displaying the section label
  @Input() label: string;

  // Used for displaying the sections inside the selected tab
  section: FormGroup;

  // Used for displaying the number of active filters within section
  activeFilterCount = 0;

  // Has the value of hierarchy path from parent to current forgroup.
  //Ex: [tab1,section1]
  sectionControlPath: string[] = [];

  //Used for showing/hiding the section
  show = true;

  //Used to find the number of field hidden based on the search text
  numberOfFieldsNotVisibile = 0;

   // Used to emit on change of field component value control changes
  @Output() updateTabActiveFilter = new EventEmitter<{count:number, value:boolean}>();

  //Event emited on change of section visibility changes i.e. show value
  @Output() updateTabVisibility = new EventEmitter<boolean>();

  @ContentChildren(BciFilterFieldComponent, { descendants: true })
  private childComponents: QueryList<BciFilterFieldComponent>;

  constructor(private bciFilterService: BciFilterService) {}

  ngAfterContentInit(): void {
    this.childComponents.forEach((child) => {
    //subscribtion called to update the section activecount based on the field value changes, then emit event to update tab active count
     child.updateSectionActiveFilter.subscribe((data) => {
        if(data) 
          this.activeFilterCount =  this.activeFilterCount + 1;
        else if(!data && this.activeFilterCount > 0 )
          this.activeFilterCount =  this.activeFilterCount - 1;
        this.updateTabActiveFilter.emit({count:this.activeFilterCount,value:data});
      });

      //subscription called to update the section visibility based on the search text, then emit event to update tab empty state
      child.updateSectionVisibility.subscribe(() => {
        this.numberOfFieldsNotVisibile = 0;
        this.childComponents.forEach((field) => field.hide && (this.numberOfFieldsNotVisibile = this.numberOfFieldsNotVisibile + 1));
        this.show =  this.numberOfFieldsNotVisibile === this.childComponents.length ? false : true;
        this.updateTabVisibility.next(this.show);
      })
    })
  }

  /**
   * Method called from parent component which used for the assigning the respective formgroup to the components variables(section, sectionControlPath) ,
   * also to detect any value changes within field, update active count and then emit events to parent Tab Component
   * @param section 
   * @param sectionPath 
   */
  setContent(section: FormGroup, sectionPath: string[]) {
    this.activeFilterCount = 0;
    this.section = section;
    this.sectionControlPath = sectionPath;
    this.bciFilterService.sectionLabelControlPathMap.set(this.label, this.sectionControlPath);

    const fieldControlNames = Object.keys(this.section.value);
    this.childComponents.forEach((child, i) => {
      const field = this.section.controls[fieldControlNames[i]] as FormControl;
      const fieldPath = [...this.sectionControlPath, fieldControlNames[i]];

      child.setField(field, fieldPath, this.label);

      //will be executed if there are any filters already applied and the filter is opened again
      if(child.active) {
        (this.activeFilterCount = this.activeFilterCount + 1);
        this.updateTabActiveFilter.emit({count:this.activeFilterCount, value:true});
      } 
    });
  }

  /**
   * Method called on click of reset within each section to set active filter count to 0, then emit event to update the tab component
   */
  onClickResetSection() {
    this.bciFilterService.resetInsideSectionFilter(this.sectionControlPath);
  }
}
