/*
 * 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 { BciFilterSectionComponent } from '../bci-filter-section/bci-filter-section.component';
import { FormGroup } from '@angular/forms';
import { distinctUntilChanged, distinctUntilKeyChanged } from 'rxjs';

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

  // holds selected tab control label value
  @Input() label: string;

  // holds selected tab value to show if tab label value is same
  tab: FormGroup;

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

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

   //Used to find the number of sections hidden based on the search text
  numberOfSectionsNotVisibile = 0

  // used to decide when to show a tab
  show = true;
  
  // Used to emit on change of tab component active count changes
  @Output() updateActiveFilterCount = new EventEmitter<number>();

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

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

  // eslint-disable-next-line no-empty-function
  constructor() {}

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

      //subscription called to update the tab visibility based on the search text, then emit event to update tab empty state inside main component
      child.updateTabVisibility.pipe( distinctUntilChanged()).subscribe(() => {
        this.numberOfSectionsNotVisibile = 0;
        this.childComponents.forEach((field) => !field.show && (this.numberOfSectionsNotVisibile = this.numberOfSectionsNotVisibile + 1));
        this.show =  this.numberOfSectionsNotVisibile === this.childComponents.length ? false : true;
        this.updateFilterVisibility.next(!this.show);
      })
    })
  }

  /**
   * Method called from parent component which used for the assigning the respective formgroup to the components variables(tabControlPath) ,
   * also to set the Section formgroup inside section component
   * @param path 
   */
  setContent(path:string[]) {
    this.activeFilterCount = 0;
    const sectionControlNames = Object.keys(this.tab.value);
    this.tabControlPath = path;
    this.childComponents.forEach((child, i) => {
      const section = this.tab.controls[sectionControlNames[i]] as FormGroup;
      const sectionPath = [...this.tabControlPath, sectionControlNames[i]];
      child.setContent(section,sectionPath);
    });
  }


  /**
   * Method called from parent component on click of reset all Filters
   */
  resetTab() {
    this.activeFilterCount = 0;
    this.childComponents.forEach((child) => {
      child.onClickResetSection();
    })
  }
}
