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

import {  Component, EventEmitter, HostBinding, Input, OnInit, Output } from '@angular/core';
import { Actions, BciFilterService } from '../service/bci-filter.service';
import { delay } from 'rxjs/operators';
import { FormControl, FormGroupDirective } from '@angular/forms';

/**
 * Component is used as a wrapper for the elements acting as a field
 */
@Component({
  selector: 'bci-filter-field',
  templateUrl: './bci-filter-field.component.html',
  styleUrls: ['./bci-filter-field.component.scss']
})
export class BciFilterFieldComponent implements OnInit {

  // To show/Hide field based on the filter search criteria
  @HostBinding('class.display-none') hide: boolean;

  // Holds the value of the current field label.
  @Input() label: string;

  // Holds the value of the current field Formgroup.
  field: FormControl;

  // Holds the value of the current field active state.
  active: boolean;

  // Holds the value of Parent Section Component label to add to list of active filters
  sectionLabel: string;

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

  //Event Emitted to update the section component on change of field value
  @Output() updateSectionActiveFilter = new EventEmitter<boolean>();

  //Event Emitted to update the section visibility based on the search criteria
  @Output() updateSectionVisibility = new EventEmitter<boolean>();

  constructor(private formGroupDirective: FormGroupDirective, private bciFilterService: BciFilterService) {}

  ngOnInit(): void {
    //Subscription called onclick of search text to check if the field label/value contains the search string
    this.bciFilterService.searchText.subscribe((data:string) => {
      this.hide = !this.bciFilterService.checkFieldLabelContainsSearchString(this.label, data) ? true : false;
      this.updateSectionVisibility.next(this.hide);
    })
  }

  /**
   * Method called from parent component which used for the assigning the respective formgroup to the components variables (field, formControlpath),
   * also to detect any value changes within the 'VALUE' form control of the field formgroup which holds following formcontrols {label, value,active}
   * @param field 
   * @param path 
   */
  setField(field: FormControl, path: string[], sectionLabel: string) {
    this.field = field;
    this.formControlPath = path;
    this.sectionLabel = sectionLabel;
    this.active = this.bciFilterService.comparePreviousValue(path,this.formGroupDirective.form);

    field.valueChanges.pipe(delay(500)).subscribe(()=> {
      const valueNotEqualToPrev = this.bciFilterService.comparePreviousValue(path,this.formGroupDirective.form);// Check is the new value is not equal to old value
      const checkIfStatusIsValid = field.status; //Check the validation state of the 'VALUE' form control within the formgroup
      const checkIfFormIsTouched = this.formGroupDirective.form.touched; // Check if the parent form is touched
          
      if (checkIfStatusIsValid === 'VALID' && !this.active &&  valueNotEqualToPrev) { //emits to parent to increase the active filter count
        this.active=true;
        this.updateSectionActiveFilter.emit(true);
      } else if(!valueNotEqualToPrev || (this.active && checkIfStatusIsValid !== 'VALID')) { //emits to parent to decrease the active filter count
        this.active=false;       
        this.updateSectionActiveFilter.emit(false);
      } else if(checkIfStatusIsValid === 'VALID' && this.active &&  valueNotEqualToPrev && checkIfFormIsTouched) {
        this.bciFilterService.activateApplyBtn = true;
      }

      this.active ? this.updateActiveFilterList(Actions.Add):  this.updateActiveFilterList(Actions.Remove);
    })
  }

  updateActiveFilterList(action: Actions) {
    const value = typeof this.field.value === 'boolean' ? this.label : this.field.value;
    this.bciFilterService.updateActiveFiltersList(action,this.sectionLabel, this.label,value);
  }

}
