import { Component, ChangeDetectionStrategy, Output, EventEmitter, ChangeDetectorRef, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { Config } from '@core/config';
import { UiFilter } from '@ui/filter';
import { Observable, Subject } from 'rxjs';
import { first, take, takeUntil } from 'rxjs/operators';
import { GoodsInSearchStore } from '../goods-in-search.store';

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

  filter: UiFilter;

  loading$: Observable<boolean>;

  message: string;

  private _onDestroy$ = new Subject();

  constructor(
    private _goodsInSearchStore: GoodsInSearchStore,
    private _breadcrumb: BreadcrumbService,
    private _cdr: ChangeDetectorRef,
    private _router: Router,
    private _config: Config
  ) {}

  ngOnInit() {
    this._initSettings();
    this._initLoading$();
  }

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

  private _initSettings() {
    this.filter = UiFilter.create(this._goodsInSearchStore.filter);
  }

  private _initLoading$() {
    this.loading$ = this._goodsInSearchStore.fetching$;
  }

  async resetFilter() {
    const queryParams = { main_qs: this.filter?.getQueryParams()?.main_qs || '' };
    this._goodsInSearchStore.resetFilter(queryParams);
    this._initSettings();
    this._cdr.markForCheck();
  }

  async applyFilter() {
    this._goodsInSearchStore.clearResults();
    this._goodsInSearchStore.setFilter(this.filter);
    this.message = undefined;

    await this.updateQueryParams();

    this._goodsInSearchStore.searchResult$.pipe(takeUntil(this._onDestroy$), take(1)).subscribe((result) => {
      if (result.error) {
      } else {
        if (result.hits > 0) {
          if (result.hits === 1) {
            const orderItem = result.result[0];
            this._router.navigate([
              `/filiale/goods/in/details/customer/${encodeURIComponent(orderItem.buyerNumber)}/order/${encodeURIComponent(
                orderItem.orderNumber
              )}/item/${orderItem.orderItemSubsetId}/${orderItem.processingStatus}`,
            ]);
          } else {
            this._router.navigate(['/filiale', 'goods', 'in', 'results'], {
              queryParams: this._goodsInSearchStore.filter.getQueryParams(),
            });
          }

          this.close.emit();
        } else {
          this.message = 'keine Suchergebnisse';
        }

        this._cdr.markForCheck();
      }
    });

    this._goodsInSearchStore.search();
  }

  async updateBreadcrumb() {
    await this._breadcrumb.addOrUpdateBreadcrumbIfNotExists({
      key: this._config.get('process.ids.goodsIn'),
      name: 'Abholfach',
      path: '/filiale/goods/in',
      tags: ['goods-in', 'main', 'filter'],
      section: 'branch',
      params: this._goodsInSearchStore.filter?.getQueryParams(),
    });
  }

  async updateQueryParams() {
    await this._router.navigate([], { queryParams: this._goodsInSearchStore.filter?.getQueryParams() });
    this.updateBreadcrumb();
  }
}
