import { Component, OnInit, ChangeDetectionStrategy, Output, EventEmitter } from '@angular/core';
import { Observable } from 'rxjs';
import { SearchStateFacade } from 'apps/sales/src/app/store/customer';
import { take } from 'rxjs/operators';
import { PrimaryFilterOption } from '../../../defs';

@Component({
  selector: 'app-shelf-primary-filters',
  templateUrl: 'shelf-primary-filters.component.html',
  styleUrls: ['./shelf-primary-filters.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ShelfPrimaryFiltersComponent implements OnInit {
  primaryFilters$: Observable<PrimaryFilterOption[]>;

  @Output() change = new EventEmitter<void>();

  constructor(private searchStateFacade: SearchStateFacade) {}

  ngOnInit() {
    this.initFilters();
  }

  handleClick(target: HTMLButtonElement) {
    const identifier = target.id;
    if (!identifier) {
      return;
    }

    this.handleUpdate({ identifier });
  }

  private handleUpdate(params: { identifier: string }) {
    this.primaryFilters$.pipe(take(1)).subscribe((currentFilters) => {
      const filterToUpdate = currentFilters.find((filter) => filter.id === params.identifier);

      if (!filterToUpdate) {
        return;
      }

      this.updateSelectedFilters({
        ...filterToUpdate,
        selected: !filterToUpdate.selected,
      });
      this.change.emit();
    });
  }

  private updateSelectedFilters(changes: PrimaryFilterOption) {
    this.searchStateFacade.setPrimaryFilters(changes);
  }

  private initFilters() {
    this.primaryFilters$ = this.searchStateFacade.primaryFilters$;
  }
}
