import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Select, Store } from '@ngxs/store';
import { RemissionSelectors } from 'apps/sales/src/app/core/store/selectors/remission.selectors';
import { filter, take } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';
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';
import { Router } from '@angular/router';

@Component({
  selector: 'app-remission-generate-shipping-document',
  templateUrl: './remission-generate-shipping-document.component.html',
  styleUrls: ['./remission-generate-shipping-document.component.scss'],
})
export class RemissionGenerateShippingDocumentComponent implements OnInit {
  isIPad = true;
  @Select(RemissionSelectors.getRemissionShippingDocumentstatus) shippingDocumentStatus$: Observable<boolean>;
  constructor(private store: Store, private router: Router) {}

  ngOnInit() {
    this.shippingDocumentStatus$
      .pipe(
        filter((data) => !isNullOrUndefined(data)),
        take(1)
      )
      .subscribe((status) => {
        if (status) {
          this.navigateToStartedRemission();
        }
      });
  }

  shippingDocumentWithGeneratedId() {
    this.navigateToStartedRemission();
  }

  shippingDocumentScanned(shippingDocumentId: string) {
    this.navigateToStartedRemission(+shippingDocumentId);
  }

  navigateToStartedRemission(shippingDocumentId?: number) {
    let path = '/remission/started';
    if (shippingDocumentId) {
      path = `/remission/started/${shippingDocumentId}`;
    }
    this.store.dispatch(
      new AddBreadcrumb(
        {
          path: path,
          name: 'Warenbegleitschein',
        },
        'remission'
      )
    );
    this.store.dispatch(new SetBranchProcessCurrentPath(path));
    this.router.navigate([path]);
  }
}
