import { Component, OnInit, Input, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { FilterOption, Filter } from '@isa/remission';
import { RemissionResourceType } from '../../models/remission-resource-type.model';
import { Select } from '@ngxs/store';
import { RemissionSelectors } from 'apps/sales/src/app/core/store/selectors/remission.selectors';
import { filter, takeUntil, distinctUntilChanged } from 'rxjs/operators';
import { Subject, Observable } from 'rxjs';
import { isNullOrUndefined } from 'util';
import { RemissionHelperService } from '../../services/remission-helper.service';

@Component({
  selector: 'app-remission-selected-filter-items',
  templateUrl: './remission-selected-filter-items.component.html',
  styleUrls: ['./remission-selected-filter-items.component.scss'],
})
export class RemissionSelectedFilterItemsComponent implements OnInit, OnDestroy {
  @Input() set inputRemissionResourceType(val: RemissionResourceType) {
    this.remissionResourceType = val;
    this.reinitializeFilters();
  }

  @Input()
  set filters(value: Filter[]) {
    this._filers = value;
    this.reinitializeFilters();
  }
  get filters() {
    return this._filers;
  }
  remissionResourceType: RemissionResourceType;
  @Select(RemissionSelectors.getRemissionSelectedFilters)
  selectedFilters$: Observable<string[]>;
  destroy$ = new Subject();
  options: FilterOption[];
  private filterOptions: string[] = [];
  private _filers: Filter[];
  constructor(private cdr: ChangeDetectorRef, private remissionHelper: RemissionHelperService) {}

  ngOnInit() {
    this.subscriptions();
  }

  subscriptions() {
    this.selectedFilters$
      .pipe(
        filter((data) => !isNullOrUndefined(data)),
        distinctUntilChanged(),
        takeUntil(this.destroy$)
      )
      .subscribe((filterOptions: string[]) => {
        this.filterOptions = filterOptions;
        this.reinitializeFilters();
      });
  }

  clearAllFilter() {
    this.remissionHelper.clearFilters();
  }

  removeOption(option: FilterOption) {
    // somehow send a filterId
    this.remissionHelper.deleteFilterOption(option);
  }

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

  private reinitializeFilters() {
    const flatFilterOptions = [];
    if (this.filters && this.filterOptions.length > 0) {
      this.filters.forEach(({ options }) => flatFilterOptions.push(...options));
      this.options = flatFilterOptions.reduce((previous, currentValue: FilterOption) => {
        const isGroupOption =
          currentValue.options === undefined
            ? this.filterOptions.includes(currentValue.id)
            : currentValue.options.every((option: FilterOption) => this.filterOptions.includes(option.id));
        const test = [
          ...previous,
          ...(isGroupOption
            ? [currentValue]
            : currentValue.options
            ? currentValue.options.filter((option: FilterOption) => this.filterOptions.includes(option.id))
            : []),
        ];
        return test;
      }, []);
    } else {
      this.options = [];
    }
    this.cdr.detectChanges();
  }
}
