import { Component, Input, ViewChild, ChangeDetectorRef, Output, EventEmitter } from '@angular/core';
import { RemissionProduct, RemissionService } from '@isa/remission';
import { RemissionHelperService } from '../../services/remission-helper.service';
import { RemissionRemoveProductFromShippingDocumentDialogComponent } from '../remission-remove-product-from-shipping-document-dialog';

@Component({
  selector: 'app-remission-shipping-document-card',
  templateUrl: './remission-shipping-document-card.component.html',
  styleUrls: ['./remission-shipping-document-card.component.scss'],
})
export class RemissionShippingDocumentCardComponent {
  @Input() product: RemissionProduct;
  @Input() remissionProcessId: number;
  @Input() shippingDocumentId: number;

  @Output() updateShippingDocument = new EventEmitter<void>();

  @ViewChild('removeProductDialog')
  removeProductDialog: RemissionRemoveProductFromShippingDocumentDialogComponent;

  showRemoveProductDialog = false;

  constructor(
    private cdr: ChangeDetectorRef,
    private remissionService: RemissionService,
    private remissionHelper: RemissionHelperService
  ) {}

  remove() {
    this.remissionService
      .removeProductFromShippingDocument({
        remissionProcessId: this.remissionProcessId,
        shippingDocumentId: this.shippingDocumentId,
        remissionProductId: this.product.id,
      })
      .toPromise()
      .then(() => {
        this.remissionHelper.addRemissionListItem(this.product);
        this.updateShippingDocument.emit();
        this.remissionHelper.requestRefetchProducts();
      });
  }

  showDialog() {
    this.showRemoveProductDialog = true;
    this.cdr.detectChanges();
    setTimeout(() => this.removeProductDialog.openDialog(), 40);
  }

  closedDialog() {
    this.showRemoveProductDialog = false;
  }
}
