import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { Store, Select } from '@ngxs/store';
import { RemissionSelectors } from 'apps/sales/src/app/core/store/selectors/remission.selectors';
import { RemissionProcess } from '@isa/remission';
import { Observable } from 'rxjs';
import { map, filter } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';
import { Router } from '@angular/router';
import { AddBreadcrumb } from 'apps/sales/src/app/core/store/actions/breadcrumb.actions';
import { SetBranchProcessCurrentPath } from 'apps/sales/src/app/core/store/actions/branch-process.actions';

@Component({
  selector: 'app-remission-open-shipping-documents-widget',
  templateUrl: './remission-open-shipping-document-widget.component.html',
  styleUrls: ['./remission-open-shipping-document-widget.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RemissionOpenShippingDocumentsWidgetComponent implements OnInit {
  @Select(RemissionSelectors.getAllUncompletedRemissions)
  uncompletedRemissions$: Observable<RemissionProcess[]>;

  numberOfOpenShippingDocuments$: Observable<number>;

  constructor(private store: Store, private router: Router) {}

  ngOnInit() {
    this.numberOfOpenShippingDocuments$ = this.getNumberOfOpenShippingDocuments();
  }

  openOverviewPage() {
    const path = 'remission/overview';
    this.store.dispatch(
      new AddBreadcrumb(
        {
          path: path,
          name: 'Offene Warenbegleitscheine',
        },
        'remission'
      )
    );
    this.store.dispatch(new SetBranchProcessCurrentPath(path, true));
    this.router.navigate([path]);
  }

  private getNumberOfOpenShippingDocuments(): Observable<number> {
    return this.uncompletedRemissions$.pipe(
      filter((remissionProcesses) => !isNullOrUndefined(remissionProcesses)),
      map((remissionProcesses) => remissionProcesses.length)
    );
  }
}
