import {
    ApiHandlerDiscreteParameter,
    createHandlerChainRunner,
    HasOnSuccess,
} from "@insite/client-framework/HandlerCreator";
import { ServiceResult } from "@insite/client-framework/Services/ApiService";
import {
    GetVmiBinsApiParameter,
    sendPdf,
    SendVmiBinPdfApiParameter,
} from "@insite/client-framework/Services/VmiBinsService";
import { getPageLinkByPageType } from "@insite/client-framework/Store/Links/LinksSelectors";
import {
    PdfBarcodeDataFieldOptions,
    PdfBarcodeFormatOptions,
    PdfLayoutOptions,
} from "@insite/client-framework/Types/PrintPdfModels";

interface Parameter extends HasOnSuccess {
    lineIds?: string[];
    layout: PdfLayoutOptions;
    barcodeFormat: PdfBarcodeFormatOptions;
    barcodeField: PdfBarcodeDataFieldOptions;
    displayFields?: string[];
    addOverlay?: boolean;
    baseParameter: GetVmiBinsApiParameter;
}

type HandlerType = ApiHandlerDiscreteParameter<Parameter, SendVmiBinPdfApiParameter, ServiceResult<{}>>;

export const CreateParameter: HandlerType = props => {
    props.apiParameter = {
        ...props.parameter.baseParameter,
        lineIds: props.parameter.lineIds,
        layout: props.parameter.layout,
        barcodeFormat: props.parameter.barcodeFormat,
        barcodeField: props.parameter.barcodeField,
        displayFields: props.parameter.displayFields,
        addOverlay: props.parameter.addOverlay,
        vmiBinDetailsPageUrl: getPageLinkByPageType(props.getState(), "VmiBinDetailsPage")!.url,
    };
};

export const CallApi: HandlerType = async props => {
    props.apiResult = await sendPdf(props.apiParameter);
};

export const ExecuteOnSuccessCallback: HandlerType = props => {
    if (props.apiResult.successful) {
        props.parameter.onSuccess?.();
    }
};

export const chain = [CreateParameter, CallApi, ExecuteOnSuccessCallback];

const sendVmiBinsPdf = createHandlerChainRunner(chain, "SendVmiBinsPdf");
export default sendVmiBinsPdf;
