import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, OnDestroy, Output, EventEmitter } from '@angular/core';
import { SearchComponentStoreService } from '@store/search-component-store';
import { Filter, UiFilter } from '@ui/filter';
import { isEqual } from 'lodash';
import { Subject } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';

@Component({
  selector: 'page-customer-search-filter',
  templateUrl: 'search-filter.component.html',
  styleUrls: ['search-filter.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CustomerSearchFilterComponent implements OnInit, OnDestroy {
  @Output()
  close = new EventEmitter();

  private _onDestroy$ = new Subject();

  filter$ = this.store.filter$.pipe(map((filter) => UiFilter.create(filter)));

  filterValuesChanged = false;

  constructor(public store: SearchComponentStoreService, private cdr: ChangeDetectorRef) {}

  ngOnInit() {}

  ngOnDestroy() {
    this._onDestroy$.next();
    this._onDestroy$.complete();
  }

  applyFilter(filter: UiFilter) {
    this.store.setFilter(filter);
    this.store.search({ clear: true });

    this.store.searchCompleted.pipe(takeUntil(this._onDestroy$)).subscribe((state) => {
      if (state.hits > 0) {
        this.close.emit();
      }
    });
  }

  resetFilter() {
    this.store.setDefaultFilter();
  }
}
