import {
  Component,
  OnInit,
  ChangeDetectionStrategy,
  Input,
  Output,
  EventEmitter,
} from '@angular/core';
import { RemissionProcess, ShippingDocument } from '@isa/remission';

@Component({
  selector: 'app-remissions-overview-card',
  templateUrl: 'remissions-overview-card.component.html',
  styleUrls: ['./remissions-overview-card.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RemissionsOverviewCardComponent implements OnInit {
  @Input()
  remissionProcess: RemissionProcess;

  @Input()
  last = false;

  @Output()
  openDetailsPage = new EventEmitter<number>();

  get shippingDocument(): ShippingDocument {
    return (
      (this.remissionProcess.shippingDocuments &&
        this.remissionProcess.shippingDocuments.find(
          (sd) => !sd.isCompleted
        )) ||
      this.remissionProcess.shippingDocuments[0]
    );
  }

  constructor() {}

  ngOnInit() {}

  onClickOpenDetails() {
    this.openDetailsPage.emit(this.remissionProcess.externalId);
  }

  private shippingDocumentExists(remissionProcess: RemissionProcess): boolean {
    return !!remissionProcess.shippingDocuments && !!this.shippingDocument;
  }

  get shippingDocumentId() {
    if (!this.shippingDocumentExists(this.remissionProcess)) {
      return null;
    }

    return this.shippingDocument.id;
  }

  get shippingDocumentIsCompleted() {
    if (!this.shippingDocumentExists(this.remissionProcess)) {
      return false;
    }

    return this.shippingDocument.isCompleted;
  }

  get numberOfShippingDocumentProducts() {
    if (!this.shippingDocumentExists(this.remissionProcess)) {
      return 0;
    }

    return this.shippingDocument.products
      ? this.shippingDocument.products.length
      : 0;
  }

  get shippingDocumentNumber() {
    if (!this.shippingDocumentExists(this.remissionProcess)) {
      return null;
    }

    return this.shippingDocument.shippingDocumentNumber;
  }

  get packageNumber() {
    if (!this.shippingDocumentExists(this.remissionProcess)) {
      return null;
    }

    return this.shippingDocument.packageNumber;
  }
}
