import {FC, useState} from "react";
import AcceptModal from "../AcceptModal/AcceptModal";
import PrintingService from "../../../utils/PrintingService";
import {useDispatch, useSelector} from "react-redux";
import {RootState} from "../../../redux/store";
import {closeReprintModal, openReprintModal} from "../../../features/reprintModal/reprintModalSlice";
import PrintingApi from "../../../api/printingApi";
import {closeLoadingModal, openLoadingModal} from "../../../features/loadingModal/loadingModalSlice";


const ReprintModal: FC = () => {
    const printerName = useSelector((state: RootState) => state.printing.printerName);
    const order = useSelector((state: RootState) => state.assembly.order);
    const isVisible = useSelector((state: RootState) => state.reprintModal.isVisible);
    const dispatch = useDispatch();
    return (<AcceptModal
        visible={isVisible}
        text={"Неудалось распечатать этикетку, повторить попытку?"}
        onAccepted={() => {
            if (!printerName || !order) return;
            dispatch(closeReprintModal());
            dispatch(openLoadingModal());
            PrintingApi.getLabel(order.databaseId).then(pdfBytes => {

                PrintingService.getInstance().printPdf(printerName, pdfBytes).then(r => {
                    dispatch(closeLoadingModal());
                    if (r) dispatch(closeReprintModal());
                    else dispatch(openReprintModal());
                });
            })
        }}
        onRefused={() => {
            dispatch(closeReprintModal())
            dispatch(closeLoadingModal());
        }}/>)
}

export default ReprintModal;