import { Component, ChangeDetectionStrategy, OnInit, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { Config } from '@core/config';
import { Subscription } from 'rxjs';
import { first } from 'rxjs/operators';
import { GoodsInSearchStore } from '../goods-in-search.store';

@Component({
  selector: 'page-goods-in-search-main',
  templateUrl: 'goods-in-search-main.component.html',
  styleUrls: ['goods-in-search-main.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class GoodsInSearchMainComponent implements OnInit, OnDestroy {
  filter$ = this._goodsInSearchStore.filter$;

  loading$ = this._goodsInSearchStore.fetching$;

  message: string;

  private _subscriptions = new Subscription();

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

  ngOnInit() {
    this._subscriptions.add(
      this._goodsInSearchStore.filter$.subscribe(() => {
        this._cdr.markForCheck();
      })
    );

    this._goodsInSearchStore.setQueryParams(this._activatedRoute.snapshot.queryParams);

    this.removeBreadcrumbs();
  }

  ngOnDestroy() {
    this._subscriptions.unsubscribe();
  }

  async removeBreadcrumbs() {
    const resultCrumbs = await this._breadcrumb
      .getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), ['goods-in', 'results'])
      .pipe(first())
      .toPromise();
    const detailsCrumbs = await this._breadcrumb
      .getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), ['goods-in', 'details'])
      .pipe(first())
      .toPromise();
    const editCrumbs = await this._breadcrumb
      .getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), ['goods-in', 'edit'])
      .pipe(first())
      .toPromise();
    const listCrumbs = await this._breadcrumb
      .getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), ['goods-in', 'list'])
      .pipe(first())
      .toPromise();
    const reservationCrumbs = await this._breadcrumb
      .getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), ['goods-in', 'reservation'])
      .pipe(first())
      .toPromise();

    const cleanupCrumbs = await this._breadcrumb
      .getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), ['goods-in', 'cleanup'])
      .pipe(first())
      .toPromise();
    const previewCrumbs = await this._breadcrumb
      .getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), ['goods-in', 'preview'])
      .pipe(first())
      .toPromise();

    resultCrumbs.forEach((crumb) => {
      this._breadcrumb.removeBreadcrumb(crumb.id, true);
    });

    detailsCrumbs.forEach((crumb) => {
      this._breadcrumb.removeBreadcrumb(crumb.id, true);
    });

    editCrumbs.forEach((crumb) => {
      this._breadcrumb.removeBreadcrumb(crumb.id, true);
    });

    listCrumbs.forEach((crumb) => {
      this._breadcrumb.removeBreadcrumb(crumb.id, true);
    });

    reservationCrumbs.forEach((crumb) => {
      this._breadcrumb.removeBreadcrumb(crumb.id, true);
    });

    cleanupCrumbs.forEach((crumb) => {
      this._breadcrumb.removeBreadcrumb(crumb.id, true);
    });

    previewCrumbs.forEach((crumb) => {
      this._breadcrumb.removeBreadcrumb(crumb.id, true);
    });
  }

  async search() {
    this._goodsInSearchStore.clearResults();
    await this.updateQueryParams();
    this.message = undefined;

    this._goodsInSearchStore.searchResult$.pipe(first()).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(),
            });
          }
        } 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();
  }
}
