import { Injectable } from '@angular/core';
import { ActionHandler } from '@core/command';
import { DomainPrinterService } from '@domain/printer';
import { PrintModalComponent, PrintModalData } from '@modal/printer';
import { UiModalService } from '@ui/modal';
import { NativeContainerService } from 'native-container';
import { OrderItemsContext } from './order-items.context';

@Injectable()
export class PrintCompartmentLabelActionHandler extends ActionHandler<OrderItemsContext> {
  constructor(
    private uiModal: UiModalService,
    private domainPrinterService: DomainPrinterService,
    private nativeContainerService: NativeContainerService
  ) {
    super('PRINT_COMPARTMENTLABEL');
  }

  async handler(data: OrderItemsContext): Promise<OrderItemsContext> {
    await this.uiModal
      .open({
        content: PrintModalComponent,
        config: { showScrollbarY: false },
        data: {
          printImmediately: !this.nativeContainerService.isUiWebview().isNative,
          printerType: 'Label',
          print: (printer) =>
            this.domainPrinterService
              .printCompartmentLabel({ printer, orderItemSubsetIds: data.items.map((item) => item.orderItemSubsetId) })
              .toPromise(),
        } as PrintModalData,
      })
      .afterClosed$.toPromise();

    return data;
  }
}
