import { Component, OnInit, ChangeDetectionStrategy, OnDestroy, ChangeDetectorRef, EventEmitter, Output } from '@angular/core';
import { RadioButtonGroup } from '@libs/ui/lib/radio-button-group';
import { Store, Select } from '@ngxs/store';
import { ProcessSelectors } from 'apps/sales/src/app/core/store/selectors/process.selectors';
import { Observable, Subject } from 'rxjs';
import { ProductSerachFilters } from 'apps/sales/src/app/core/models/product-search-filters.model';
import { filter, takeUntil } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';
import { SetProcessProductFilters } from 'apps/sales/src/app/core/store/actions/process.actions';

@Component({
  selector: 'app-interactive-filters',
  templateUrl: './interactive-filters.component.html',
  styleUrls: ['./interactive-filters.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class InteractiveFiltersComponent implements OnInit, OnDestroy {
  @Select(ProcessSelectors.getProductFilters) filters$: Observable<ProductSerachFilters>;
  destroy$ = new Subject();
  radioButtonGroup: RadioButtonGroup;
  acrhiveFilter: boolean;
  @Output() filtersUpdated = new EventEmitter<ProductSerachFilters>();

  constructor(private store: Store, private cdr: ChangeDetectorRef) {}

  ngOnInit() {
    this.filters$
      .pipe(
        filter((data) => !isNullOrUndefined(data)),
        takeUntil(this.destroy$)
      )
      .subscribe((filters: ProductSerachFilters) => {
        this.radioButtonGroup = filters.radioButtonGroup;
        this.acrhiveFilter = filters.archiveFilters;
        this.cdr.detectChanges();
      });
  }

  filterUpdate(_radioButtonGroup: RadioButtonGroup) {
    this.radioButtonGroup = _radioButtonGroup;
    const data = this.updateFiltersObject();
    this.store.dispatch(new SetProcessProductFilters(data));
    this.filtersUpdated.emit(data);
  }

  archiveFilter(active: boolean) {
    this.acrhiveFilter = active;
    const data = this.updateFiltersObject();
    this.store.dispatch(new SetProcessProductFilters(data));
    this.filtersUpdated.emit(data);
  }

  private updateFiltersObject(): ProductSerachFilters {
    return {
      radioButtonGroup: this.radioButtonGroup,
      archiveFilters: this.acrhiveFilter,
    };
  }

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