function saveLastDocumentType(docType) {
    localStorage.setItem('LastDocumentType', docType);
}

function clearLastDocumentType() {
    localStorage.removeItem("LastDocumentType");
}

function isNewDocumentType(docType) {
    let lastDocumentType = localStorage.getItem('LastDocumentType');
    return lastDocumentType !== docType;
}

async function checkLpfrConnection(LPFRCheckServerUrl, onSuccess, onFail) {
    if (!LPFRCheckServerUrl) {
        if (onFail) onFail();
        return false;
    }

    var LPFRAvailable = true;

    //Check if LPFR service available
    await fetch(LPFRCheckServerUrl, {
        method: "GET",
        headers: { 'Content-Type': 'application/json' },
    }).then((response) => {
        if (!response.ok) throw (response.statusText);
    }).catch((error) => {
        if (onFail) onFail(error);
        LPFRAvailable = false;
    });

    if (LPFRAvailable) {
        if (onSuccess) onSuccess();
    }

    return LPFRAvailable;
}

async function checkLpfrConnectionWithToast(LPFRCheckServerUrl, successMessage, FailMessage) {
    let lpfrConnectionSuccess = await checkLpfrConnection(LPFRCheckServerUrl, function () {
        $().customToast({
            type: 'success',
            text: successMessage,
            autoCloseDelay: 5000
        });
    }, function () {
        $().customToast({
            type: 'error',
            text: FailMessage
        });
    });

    return lpfrConnectionSuccess;
}

function openLpfrPinModal(LPFRPinUrl, title, okButtonText, cancelButtonText, onSuccess, onFail, onCommunicationError, localization) {
    $().customModal({
        customTitle: true,
        title: title,
        destroyOnClose: true,
        showCloseButton: false,
        maxWidth: "350px",
        type: "question",
        id: 'lpfrPinModal',
        content: "<div class='row' style='width:100%'><label class='form-label col-xs-4' style='text-align: right;'>PIN</label><div class='col-xs-8'><input class='form-control' placeholder='PIN' style='text-align: right;' /></div></div>",
        onOpen: function () {
            $("#lpfrPinModal input").focus();
            $("#lpfrPinModal input").on("keyup", function (e) {
                if (e.keyCode === 13) {
                    e.preventDefault();
                    $("#lpfrPinModal button").eq(1).click();
                }
            });
        },
        buttons: [
            {
                text: cancelButtonText,
                icon: 'fa fa-times',
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: okButtonText,
                action: async function () {
                    return fetch(LPFRPinUrl, {
                        method: "POST",
                        //headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                        body: $("#lpfrPinModal input").val()
                    }).then((response) => response.json()
                    ).then(async (pinData) => {
                        if (pinData === "0100") {
                            $("#lpfrPinModal").customModal("close");
                            if (onSuccess) onSuccess();
                            return;
                        }

                        throw pinData;
                    }).catch((error) => {
                        let errorMessage;
                        if (localization) {
                            errorMessage = localization[error];
                        }

                        let displayCommunicationError = false;
                        if (!errorMessage) {
                            switch (error) {
                                case '2100':
                                    errorMessage = 'PIN code is wrong for the inserted card. Secure element responded with 0x6302 or 0x6303';
                                    break;
                                case '2110':
                                    errorMessage = 'The number of allowed PIN entries exceeded. The card is locked for further use and has to be returned to Tax Office. Secure element responded with 0x6310';
                                    break;
                                case '1300':
                                    errorMessage = 'E-SDC detects that the smart card is not inserted (or E-SDC fails to connect to it due to card or card reader issues or some other internal malfunction)';
                                    break;
                                case '2220':
                                    errorMessage = 'E-SDC cannot connect to the Secure Element applet';
                                    break;
                                case '2400':
                                    errorMessage = 'SDC device is not fully configured for invoice signing (i.e. tax rates or verification URL are missing etc.)';
                                    break;
                                default:
                                    errorMessage = 'PIN error'
                                    displayCommunicationError = true;
                                    break;
                            }
                        }

                        $("#lpfrPinModal input").blur();
                        if (displayCommunicationError) {
                            let communicationButton = '<div class="well well-sm well-bg clickable-icon m-b-sm m-t-sm" data-dismiss="modal" onclick="window.open(\'' + LPFRPinUrl + '\', \'_blank\')">';
                            communicationButton += '<div class="row full-width"><div class="col-xs-2"><div class="icon-arrow-right"></div></div>';
                            communicationButton += '<div class="col-xs-10 well-text-margin"><strong>' + localization["communicationButtonTitle"] + '</strong><p class="no-margins">' + localization["communicationButtonActionText"] + ' ' + LPFRPinUrl + '</p></div>';
                            communicationButton += '</div></div>';

                            let manualButton = '<div class="well well-sm well-bg clickable-icon m-b-sm" data-dismiss="modal" onclick="window.open(\'' + localization["lpfrCommunicationHelp"] + '\', \'_blank\')">';
                            manualButton += '<div class="row full-width"><div class="col-xs-2"><div class="icon-help icon-full-size"></div></div>';
                            manualButton += '<div class="col-xs-10 well-text-margin"><strong>' + localization["manualButtonTitle"] + '</strong><p class="no-margins">' + localization["manualButtonActionText"] + '</p></div>';
                            manualButton += '</div></div>';

                            $().customModal({
                                destroyOnClose: true,
                                showCloseButton: true,
                                title: localization["communicationModalTitle"],
                                type: "modal",
                                maxWidth: "520px",
                                content: "<div>" + localization["communicationModalErrorMessage"] + "</div>" + communicationButton + manualButton,
                                closeOtherModals: false
                            });

                            if (onCommunicationError) onCommunicationError();
                            return;
                        }

                        if (onFail) onFail("Error verifying PIN (" + error+ "): " + errorMessage);
                    });
                },
                type: 'primary',
                closeOnAction: false
            }
        ]
    });
}

async function getLpfrData(lpfrFiscalizationDataUrl) {
    var lpfrData;
    await fetch(lpfrFiscalizationDataUrl, {
        method: "GET",
        headers: { 'Content-Type': 'application/json' }
    }).then((response) => lpfrData = response.json());

    return lpfrData;
}

async function lpfrFiscalization(LPFRCheckServerUrl, LPFRServerUrl, LPFRUpdateInvoiceUrl, LPFRJson, acKey, onSuccess, onFail) {
    //Send data to LPFR service
    await fetch(LPFRServerUrl, {
        method: "POST",
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Accept-Language': 'sr-Cyrl-RS;en-US' },
        body: LPFRJson
    }).then((response) => response.json()
    ).then(async (lpfrData) => {
        if (lpfrData && lpfrData.modelState && lpfrData.modelState.length > 0) {
            if (lpfrData.modelState.some(x => x.errors.some(s => s === "2310"))) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: $("#AllTaxesNeedFiscalCodeLoc").val(),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#ConfirmLoc").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                throw "";
            } else
                throw lpfrData.message;
        }

        //Send response to pHE_UpdateResponse_RS
        await fetch(LPFRUpdateInvoiceUrl, {
            method: "POST",
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ acKey: acKey, json: JSON.stringify(lpfrData) })
        }).then((response) => response.json()
        ).then(async (savingData) => {
            if (!savingData.success) throw savingData.error;

            if (onSuccess) await onSuccess();
        }).catch(async (error) => {
            if (onFail) await onFail(error);
        });
    }).catch((error) => {
        if (onFail) onFail(error);
    });
}