import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { ModalService } from '@libs/ui';
import { RemissionService, RemissionPlacementType } from '@isa/remission';
import { take, filter } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';

@Component({
  selector: 'app-remission-add-product-to-shipping-document-partially-dialog',
  templateUrl: './remission-add-product-to-shipping-document-partially-dialog.component.html',
  styleUrls: ['./remission-add-product-to-shipping-document-partially-dialog.component.scss'],
})
export class RemissionAddProductToShippingDocumentPartiallyDialogComponent implements OnInit {
  id = 'remission-add-product-to-shipping-document-partially-modal';
  @Input() quantity: number;
  @Input() placementType: RemissionPlacementType;
  @Output() add = new EventEmitter();
  @Output() closed = new EventEmitter<{
    quantity: number;
    placementType: string;
  }>();

  placementTypes: RemissionPlacementType[];
  loading = false;
  predefinedRemissionQuantity: number;

  constructor(private modalService: ModalService, private remissionService: RemissionService) {}

  ngOnInit() {
    this.remissionService
      .getPlacementTypes()
      .pipe(
        filter((data) => !isNullOrUndefined(data) && data.length > 0),
        take(1)
      )
      .subscribe((placementTypes) => {
        this.placementTypes = placementTypes;
      });

    this.setPredefinedRemissionQuantity(this.quantity);
  }

  setPredefinedRemissionQuantity(totalRemissionQuantity: number) {
    this.predefinedRemissionQuantity = totalRemissionQuantity;
  }

  public openDialog() {
    this.loading = false;
    this.modalService.open(this.id);
  }

  closeDialog() {
    this.modalService.close(this.id);
    this.closed.emit();
  }

  addProduct() {
    this.loading = true;
    if (isNullOrUndefined(this.quantity) || this.quantity < 0) {
      return;
    }
    this.add.emit({
      quantity: this.quantity,
      placementType: this.placementType,
      predefinedRemissionQuantity: this.predefinedRemissionQuantity,
    });
  }

  placementUpdated(placementType: RemissionPlacementType) {
    this.placementType = placementType;
  }

  public stopLoading() {
    this.loading = false;
  }
}
