import {
  ChangeDetectionStrategy,
  Component,
  OnInit,
  Input,
  ViewChildren,
  QueryList,
  ChangeDetectorRef,
  OnDestroy,
  EventEmitter,
  Output,
} from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil, distinctUntilChanged } from 'rxjs/operators';
import { Filter, RemissionService } from '@isa/remission';
import { RemissionResourceType } from '../../models/remission-resource-type.model';
import { RemissionFilterItemComponent } from '../remission-filter-item/remission-filter-item.component';

@Component({
  selector: 'app-remission-filters',
  templateUrl: './remission-filters.component.html',
  styleUrls: ['./remission-filters.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RemissionFiltersComponent implements OnInit, OnDestroy {
  @Input() remissionProcessId: number;

  @Input()
  set remissionResourceType(val: RemissionResourceType) {
    this._remissionResourceType = val;
  }
  get remissionResourceType(): RemissionResourceType {
    return this._remissionResourceType;
  }
  @ViewChildren('filterItem') filterItems: QueryList<RemissionFilterItemComponent>;

  @Output() toggleChange = new EventEmitter();

  filters: Filter[];
  destroy$ = new Subject();
  loadItems = true;
  private _remissionResourceType: RemissionResourceType;
  private _filtersEpanded: boolean[] = [];

  constructor(private cdr: ChangeDetectorRef, private remissionService: RemissionService) {}

  ngOnInit() {
    this.subscriptions();
  }

  ngOnDestroy() {
    this.destroy$.next();
  }

  subscriptions() {
    this.loadItems = false;
    this.remissionService
      .getFilters({ remissionProcessId: this.remissionProcessId })
      .pipe(distinctUntilChanged(), takeUntil(this.destroy$))
      .subscribe(this.remissionFiltersSubscription);
  }

  remissionFiltersSubscription = (remissionFilters: Filter[]) => {
    // Remove an empty filter
    this.filters = remissionFilters.filter((filter) => filter.options.length > 0);
    this.loadItems = true;
    this.cdr.markForCheck();
  };

  closeOtherFilters(currentFilterId: string) {
    if (this.filterItems) {
      this.filterItems.forEach((filterItem) => {
        filterItem.closeNotCurrentFilters(currentFilterId);
      });
    }
  }

  toggleChangeEmit(value: boolean, index: number) {
    this._filtersEpanded[index] = value;
    const emit = !!this._filtersEpanded.find((v) => v);
    this.toggleChange.emit(!!emit);
  }
}
