import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { Config } from '@core/config';
import { DomainRemissionService } from '@domain/remission';
import { ReturnDTO } from '@swagger/remi';
import { UiErrorModalComponent, UiModalService } from '@ui/modal';
import { UiSearchboxNextComponent } from '@ui/searchbox';
import { Subject } from 'rxjs';
import { first } from 'rxjs/operators';

@Component({
  selector: 'page-create-remission',
  templateUrl: 'create-remission.component.html',
})
export class CreateRemissionComponent implements OnInit {
  @ViewChild(UiSearchboxNextComponent)
  searchboxComponent: UiSearchboxNextComponent;

  get processId() {
    return this._config.get('process.ids.remission');
  }

  loading$ = new Subject<boolean>();

  hint$ = new Subject<string>();

  get supplierId(): number {
    return this._activatedRoute?.snapshot?.queryParams?.supplier ? +this._activatedRoute?.snapshot?.queryParams?.supplier : 2; // Set Supplier Blank as Default
  }

  get source(): string {
    return this._activatedRoute?.snapshot?.queryParams?.source;
  }

  constructor(
    private _activatedRoute: ActivatedRoute,
    private readonly _domainRemissionService: DomainRemissionService,
    private readonly _modal: UiModalService,
    private readonly _router: Router,
    private readonly _breadcrumb: BreadcrumbService,
    private readonly _config: Config
  ) {}

  async ngOnInit() {
    await this.removeBreadcrumbs();
    await this.addBreadcrumbIfNotExists();
  }

  async startRemission(receiptNumber?: string) {
    try {
      const returnGroup = this._activatedRoute.snapshot.params?.returnGroup;

      const supplier = await this.getSupplier();
      const returnDTO = await this.createReturn(supplier.id, returnGroup);
      const receipt = await this.createReceipt({ returnDTO, receiptNumber });
      if (receipt) {
        await this.navigateToList(returnDTO.id);
      } else {
        return undefined;
      }
    } catch (error) {
      console.error(error);
      this._modal.open({ content: UiErrorModalComponent, title: 'Fehler beim Starten der Remission', data: error });
      return undefined;
    }
  }

  async getSupplier() {
    const suppliers = await this._domainRemissionService.getSuppliers().pipe(first()).toPromise();
    return suppliers.find((s) => s.id === this.supplierId);
  }

  async createReturn(supplierId: number, returnGroup: string) {
    return await this._domainRemissionService.createReturn(supplierId, returnGroup);
  }

  async createReceipt({ returnDTO, receiptNumber }: { returnDTO: ReturnDTO; receiptNumber?: string }) {
    return await this._domainRemissionService.createReceipt(returnDTO, receiptNumber);
  }

  async navigateToList(returnId: number) {
    await this._router.navigate(['/filiale', 'remission', returnId, 'list'], {
      queryParams: { ...this._activatedRoute.snapshot.queryParams, supplier: this.supplierId, source: this.source },
    });
  }

  async addBreadcrumbIfNotExists() {
    await this._breadcrumb.addBreadcrumbIfNotExists({
      key: this._config.get('process.ids.remission'),
      name: 'Warenbegleitschein eröffnen',
      path: '/filiale/remission/create',
      params: this._activatedRoute.snapshot.queryParams,
      section: 'branch',
      tags: ['remission', 'create'],
    });
  }

  async removeBreadcrumbs() {
    await this._breadcrumb.removeBreadcrumbsByKeyAndTags(this.processId, ['remission', 'shipping-documents']);
    await this._breadcrumb.removeBreadcrumbsByKeyAndTags(this.processId, ['remission', 'add-product']);
    await this._breadcrumb.removeBreadcrumbsByKeyAndTags(this.processId, ['remission', 'finish-shipping-document']);
    await this._breadcrumb.removeBreadcrumbsByKeyAndTags(this.processId, ['remission', 'finish-remission']);
  }
}
