import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { Config } from '@core/config';
import { DomainRemissionService } from '@domain/remission';
import { ReturnDTO } from '@swagger/remi';
import { DateAdapter } from '@ui/common';
import { combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'page-shipping-document-list',
  templateUrl: 'shipping-document-list.component.html',
  styleUrls: ['shipping-document-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ShippingDocumentListComponent implements OnInit {
  returns$: Observable<ReturnDTO[]>;

  constructor(
    private _remissionService: DomainRemissionService,
    private _breadcrumb: BreadcrumbService,
    private _config: Config,
    private _activatedRoute: ActivatedRoute,
    private readonly _dateAdapter: DateAdapter
  ) {}

  ngOnInit() {
    this.addBreadcrumbIfNotExists();
    this.removeDetailBreadcrumbs();
    this.returns$ = combineLatest([
      this._remissionService.getReturns({ returncompleted: false }),
      this._remissionService.getReturns({ returncompleted: true, start: this._dateAdapter.addCalendarDays(new Date(), -7) }),
    ]).pipe(
      map(([returns, returnsLastWeek]) => {
        return [...returns, ...returnsLastWeek];
      })
    );
  }

  addBreadcrumbIfNotExists() {
    this._breadcrumb.addBreadcrumbIfNotExists({
      key: this._config.get('process.ids.remission'),
      name: 'Offene Warenbegleitscheine',
      path: '/filiale/remission/shipping-documents',
      section: 'branch',
      params: this._activatedRoute?.snapshot?.queryParams,
      tags: ['remission', 'shipping-documents'],
    });
  }

  removeDetailBreadcrumbs() {
    this._breadcrumb.removeBreadcrumbsByKeyAndTags(this._config.get('process.ids.remission'), [
      'remission',
      'shipping-documents',
      'details',
    ]);
  }
}
