import { ChangeDetectionStrategy, Component, EventEmitter, OnInit, Output } from '@angular/core';
import { UiFilter } from '@ui/filter';
import { Observable } from 'rxjs';
import { map, take } from 'rxjs/operators';
import { ArticleSearchService } from '../article-search.store';

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

  fetching$: Observable<boolean>;

  filter$: Observable<UiFilter>;

  searchboxHint$ = this.articleSearch.searchboxHint$;

  constructor(private articleSearch: ArticleSearchService) {}

  ngOnInit() {
    this.fetching$ = this.articleSearch.fetching$;
    this.filter$ = this.articleSearch.filter$.pipe(
      map((filter) => UiFilter.create(filter))
      // tap((filter) =>
      //   filter.fromQueryParams({
      //     main_qs: 'harry potter',
      //     filter_format: 'eb;!hc',
      //     filter_dbhwgr: '110;121',
      //     main_author: 'author',
      //     filter_region: '9780*|9781*;97884*',
      //     'filter_reading-age': '1-10',
      //     main_stock: '1-',
      //   })
      // )
    );
  }

  applyFilter(value: UiFilter) {
    this.articleSearch.setFilter(value);
    this.articleSearch.search({ clear: true });
    this.articleSearch.searchCompleted.pipe(take(1)).subscribe((s) => {
      if (s.searchState === '') {
        this.close.emit();
      }
    });
  }

  resetFilter(value: UiFilter) {
    const queryParams = { main_qs: value?.getQueryParams()?.main_qs || '' };
    this.articleSearch.setDefaultFilter(queryParams);
  }
}
