import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { Config } from '@core/config';
import { DomainGoodsService } from '@domain/oms';
import { Observable } from 'rxjs';
import { map, shareReplay, switchMap } from 'rxjs/operators';

@Component({
  selector: 'page-goods-in-edit',
  templateUrl: 'goods-in-edit.component.html',
  styleUrls: ['goods-in-edit.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class GoodsInEditComponent implements OnInit {
  orderNumber$: Observable<string> = this._activatedRoute.params.pipe(
    map((params) => decodeURIComponent(params.orderNumber ?? '') || undefined)
  );

  items$ = this.orderNumber$
    .pipe(switchMap((orderNumber) => this._domainGoodsInService.getWareneingangItemByOrderNumber(orderNumber)))
    .pipe(
      map((response) => response.result),
      shareReplay()
    );

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _breadcrumb: BreadcrumbService,
    private _domainGoodsInService: DomainGoodsService,
    private _router: Router,
    private readonly _config: Config
  ) {}

  ngOnInit() {
    this.updateBreadcrumb();
  }

  async updateBreadcrumb() {
    const orderNumber = this._activatedRoute.snapshot.params.orderNumber;
    const orderItemId = this._activatedRoute.snapshot.params.orderItemId;
    const processingStatus = this._activatedRoute.snapshot.params.processingStatus;
    await this._breadcrumb.addOrUpdateBreadcrumbIfNotExists({
      key: this._config.get('process.ids.goodsIn'),
      name: 'Bearbeiten',
      path: `/filiale/goods/in/details/order/${encodeURIComponent(orderNumber)}/item/${orderItemId}/${processingStatus}/edit`,
      section: 'branch',
      tags: ['goods-in', 'edit', orderNumber],
    });
  }

  navigateToDetailsPage({ options }: { options?: { processingStatus?: number } }) {
    const customerNumber = this._activatedRoute.snapshot.params.customerNumber;
    const orderNumber = this._activatedRoute.snapshot.params.orderNumber;
    const orderItemId = this._activatedRoute.snapshot.params.orderItemId;
    const processingStatus = options?.processingStatus ? options.processingStatus : this._activatedRoute.snapshot.params.processingStatus;
    this._router.navigate([
      `/filiale/goods/in/details/customer/${encodeURIComponent(customerNumber)}/order/${encodeURIComponent(
        orderNumber
      )}/item/${orderItemId}/${processingStatus}`,
    ]);
  }
}
