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

import { ActiveDescendantKeyManager } from '@angular/cdk/a11y';
import { AfterContentInit, ChangeDetectorRef, Component, ContentChildren, EventEmitter, HostListener, Input, OnDestroy, OnInit, Output, QueryList } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { BciSharedIntl } from '../shared-intl';
import { FilterEntryComponent } from './filter-entry/filter-entry.component';

@Component({
  selector: 'bci-filter-picker',
  templateUrl: './filter-picker.component.html',
  styleUrls: ['./filter-picker.component.scss'],
})
export class FilterPickerComponent implements AfterContentInit,OnInit, OnDestroy {
  
  /** Used for component-wide show/hide based on conditions */
  @Input() showModal = true;
 
  @Output()
  public filter: EventEmitter<string> = new EventEmitter<string>();

  @Output()
  // eslint-disable-next-line @angular-eslint/no-output-native
  public close: EventEmitter<string> = new EventEmitter<string>();

  /** Used for component-wide unsubscription on destroy. */
  private ngUnsubscribe = new Subject<void>();

  /** Used for getting Filter Entry Component list as a child content */
  @ContentChildren(FilterEntryComponent)
  private childFilterEntryComponent: QueryList<FilterEntryComponent>;

  /** Define Active Descendant Key Manager to manage key event on each item*/
  private keyManager: ActiveDescendantKeyManager<FilterEntryComponent>;

  constructor(public intl: BciSharedIntl, private changeDetector: ChangeDetectorRef) {}

  @HostListener('keydown', ['$event'])
  onKeydown(event) {
    if(event.target.classList.contains("mat-list-item"))
    this.keyManager.onKeydown(event);
  }

  ngAfterContentInit(): void {
    this.keyManager = new ActiveDescendantKeyManager(this.childFilterEntryComponent).withWrap().withTypeAhead();
  }

  ngOnInit() {
    this.intl.changes.pipe(takeUntil(this.ngUnsubscribe)).subscribe(() => this.changeDetector.detectChanges());
  }

  ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

  applyFilters() {
    this.filter.emit();
  }

  closeModal() {
    this.close.emit();
  }
}
