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

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

  async handler(data: OrderItemsContext): Promise<OrderItemsContext> {
    await this.uiModal
      .open({
        content: PrintModalComponent,
        config: { showScrollbarY: false },
        data: {
          printImmediately: !this.nativeContainerService.isUiWebview().isNative,
          printerType: 'Label',
          print: async (printer) => {
            try {
              for (const group of groupBy(data?.receipts, (receipt) => receipt?.buyer?.buyerNumber)) {
                await this.domainPrinterService.printShippingNote({ printer, receipts: group?.items?.map((r) => r?.id) }).toPromise();
              }
              return {
                error: false,
              };
            } catch (error) {
              console.error(error);
              return {
                error: true,
                message: error?.message || error,
              };
            }
          },
        } as PrintModalData,
      })
      .afterClosed$.toPromise();

    return data;
  }
}
