(function ($) {
    var BIDSPIRIT_SERVER = window.bidSpiritServer,
        BIDSPIRIT_API_BASE = BIDSPIRIT_SERVER + "api/thirdparty/v1/",
        REST_API_BASE = "/wp-json/bidspirit/v1/",
        LANG = window.bidSpiritLang,
        currencySymbol = window.bidSpiritCurrency !== "" ? window.bidSpiritCurrency : "$",
        bidspiritSessionId,
        bidspiritAuthToken,
        bidspiritUser,
        currentAuctionNumber,
        currentLotIndex,
        allIncrementsPrices = null,
        currentItemInfoResponse = null,
        currentItemInfo = null,
        auctionApprovalState = null,
        countriesList = null,
        auctionHouseData = {
            disclaimer: null,
            email: null,
            enablePrebidsUnderStartPrice: null,
            houseCommissionVatRule: null,
            info: null,
            name: null,
            noVatByDefault: null,
            phone: null,
            requireIdPhoto: null,
            vat: null,
            noVatOnCommission: null,
        },
        auctionInfo = {
            approvalRequired: null,
            paymentMethodRequired: null,
            absenteeBidsEnabled: null,
            address: null,
            automaticAuction: null,
            commission: null,
            commissionInfo: null,
            currency: null,
            days: null,
            displayStartPriceInCatalog: null,
            id: null,
            info: null,
            lastCatalogUpdate: null,
            name: null,
            number: null,
            showEstimatedPriceInItemsList: null,
            state: null
        },
        auctionItemInfo = {},
        paymentMethods = [],
        auctionSettingsData = {
            requireUserId: null,
            requireTaxNumber: null,
            documentUrlBase: null,
            stripePublicKey: null,
            bidspiritPortal: null,
            alertsEnabled: null
        },
        imageBlank = (typeof AuctionForgePlugin !== "undefined" && AuctionForgePlugin.imageBlank) ? AuctionForgePlugin.imageBlank : "/wp-content/plugins/uco-auctions/img/not_found.jpg",
        triggerClass = "is-load-earlier";
    bidspiritApi = {
        lang: LANG,
        getBidspiritSessionId: function () {
            return bidspiritSessionId;
        },
        setBidspiritSessionId: function (sessionId) {
            if (sessionId === undefined) {
                try {
                    sessionId = localStorage.getItem("bidspiritSessionId") || "";
                } catch (e) {
                    console.error("Local storage disabled");
                }
            }

            bidspiritSessionId = sessionId;
        },
        getAuthToken: function (apiAction) {
            if (apiAction !== undefined && apiAction === "users/initSession" && bpGetQueryParams("authToken") !== null) {
                return bpGetQueryParams("authToken");
            }

            try {
                bidspiritAuthToken = localStorage.getItem("bidspiritAuthToken");
            } catch (e) {
                console.error("Local storage disabled");
                bidspiritAuthToken = "";
            }

            return bidspiritAuthToken;
        },
        setAuthToken: function (authToken) {
            try {
                localStorage.setItem("bidspiritAuthToken", authToken);
            } catch (e) {
                console.error("Local storage disabled");
            }

            bidspiritAuthToken = authToken;
        },
        getBidspiritUser: function () {
            return bidspiritUser;
        },
        setBidspiritUser: function (user) {
            bidspiritUser = user;
            let successMessage = "";

            if (bidspiritUser !== undefined) {
                if (bidspiritUser.honorific === undefined) {
                    bidspiritUser.honorific = "";
                }

                if (bidspiritUser.firstName === undefined) {
                    bidspiritUser.firstName = "";
                }

                if (bidspiritUser.lastName === undefined) {
                    bidspiritUser.lastName = "";
                }

                successMessage = window.bs_lang.login_success_hello + ", " + bidspiritUser.firstName;

                if (bidspiritUser.honorific !== "") {
                    successMessage = window.bs_lang.login_success_full_hello.replace(/%s1/, bidspiritUser.honorific).replace(/%s2/, bidspiritUser.firstName).replace(/%s3/, bidspiritUser.lastName);
                }

                if (window.bs_lang.login_success_hello_custom !== "" && bidspiritUser.honorific !== "") {
                    successMessage = window.bs_lang.login_success_hello_custom.replace(/%s1/, bidspiritUser.honorific).replace(/%s2/, bidspiritUser.firstName).replace(/%s3/, bidspiritUser.lastName);
                } else if (window.bs_lang.login_success_hello_custom_default !== "" && bidspiritUser.honorific === "") {
                    successMessage = window.bs_lang.login_success_hello_custom_default.replace(/%s1/, bidspiritUser.firstName).replace(/%s2/, bidspiritUser.lastName);
                }

                bidspiritUser.successMessage = successMessage;
            }
        },
        getAuctionApprovalState: function () {
            return auctionApprovalState;
        },
        setAuctionApprovalState: function (value) {
            auctionApprovalState = value;
        },
        getCountriesList: function () {
            return countriesList;
        },
        setCountriesList: function (value) {
            countriesList = value;
        },
        getAuctionHouseData: function () {
            return auctionHouseData;
        },
        setAuctionHouseData: function (value) {
            auctionHouseData = value;
        },
        getAuctionInfo: function () {
            return auctionInfo;
        },
        setAuctionInfo: function (value) {
            auctionInfo = value;
        },
        getAuctionItemInfo: function () {
            return auctionItemInfo;
        },
        setAuctionItemInfo: function (value) {
            auctionItemInfo = value;
        },
        setIncrementsPrices: function (callback) {
            if (allIncrementsPrices === null) {
                allIncrementsPrices = bidspiritApi.getAuctionInfo().increments;
            } else {
                callback(allIncrementsPrices);
            }
        },
        getIncrementsPrices: function () {
            return allIncrementsPrices;
        },
        stripeLoad: function (callback) {
            var classTrigger = "stripe-load";

            if (document.body.classList.contains(classTrigger)) {
                callback();
            } else {
                $.getScript("https://js.stripe.com/v3/").done(function (script, textStatus) {
                    callback();
                    console.info(textStatus + " Stripe load");
                    document.body.classList.add(classTrigger);
                }).fail(function (jqxhr, settings, exception) {
                    console.error("Error Stripe load", jqxhr, settings, exception);
                });
            }
        },

        getLinkOnLive() {
            let lat = "";

            if (bidspiritUser !== undefined && bidspiritUser.liveAuctionToken !== undefined) {
                lat = "?lat=" + bidspiritUser.liveAuctionToken;
            }

            return BIDSPIRIT_SERVER + lat;
        },

        bidspiritQuery: bidspiritQuery,
        bidspiritPostQuery: bidspiritPostQuery,
        hangUpEvent: hangUpEvent
    };

    function ajaxQuery(params, apiAction, data, callback, errorCallback, alwaysCallback) {
        $.ajax(params).done(function (response) {
            if (callback !== undefined) {
                callback(response);
            }
        }).fail(function () {
            if (errorCallback !== undefined) {
                errorCallback();
            }
        }).always(function () {
            if (alwaysCallback !== undefined) {
                alwaysCallback();
            }
        });
    }

    function restQuery(apiCall, method, data, callback) {
        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                if (callback !== undefined) {
                    callback(this.responseText);
                }
            }
        };

        apiCall = REST_API_BASE + apiCall + "?" + new URLSearchParams(data).toString();
        xhttp.open(method, apiCall, true);
        xhttp.setRequestHeader("Content-type", "application/json");
        xhttp.send();
    }

    function bidspiritQuery(apiAction, data, callback, errorCallback, alwaysCallback) {
        if (bpGetQueryParams("sessionId") !== null) {
            data.sessionId = bpGetQueryParams("sessionId");
        }

        ajaxQuery({
            url: BIDSPIRIT_API_BASE + apiAction + ".api",
            data: data,
            timeout: 0,
            beforeSend: function (request) {
                request.setRequestHeader("BIDSPIRIT-AUTH-TOKEN", bidspiritApi.getAuthToken(apiAction));
            },
            xhrFields: {
                withCredentials: true
            }
        }, apiAction, data, callback, errorCallback, alwaysCallback);
    }

    function bidspiritPostQuery(apiAction, data, callback, errorCallback, alwaysCallback) {
        if (bpGetQueryParams("sessionId") !== null) {
            data.sessionId = bpGetQueryParams("sessionId");
        }

        ajaxQuery({
            url: BIDSPIRIT_API_BASE + apiAction + ".api",
            data: data,
            type: "POST",
            timeout: 0,
            beforeSend: function (request) {
                request.setRequestHeader("BIDSPIRIT-AUTH-TOKEN", bidspiritApi.getAuthToken(apiAction));
            },
            xhrFields: {
                withCredentials: true
            }
        }, apiAction, data, callback, errorCallback, alwaysCallback);
    }

    function hangUpEvent(name, data, target) {
        var event = jQuery.Event(name);
        event.response = data;

        if (target === undefined) {
            $("body").trigger(event);
        } else {
            target.trigger(event);
        }
    }

    let loginMessage = "Please login.";

    function toastyError(message) {
        if (message === undefined) {
            message = 'There has been a critical error';
        }

        jQuery.toast({
            title: 'Error.',
            showProgress: 'bottom',
            classProgress: 'blue',
            class: 'error',
            message: message,
            displayTime: 10000,
        });
    }

    function doSyncProcess(action, alwaysCallback) {
        return (async function (action) {
            await $.ajax({
                url: '/wp-json/bidspirit/v1/re-sync',
                headers: {"X-WP-Nonce": ScoreSettings.nonce},
                type: 'POST',
                dataType: 'json',
                data: {
                    do: action
                }
            })
            .done(function (response) {
                console.info(response);
                if (response.success) {
                    return Promise.resolve();
                } else {
                    toastyError(window.bs_lang.not_found);
                    return Promise.reject();
                }
            })
            .fail(function (response) {
                toastyError(loginMessage);
                console.error(response);
                return Promise.reject();
            })
            .always(function () {
                alwaysCallback();
            });
        })(action);
    }

    function isNotAuth(isAdmin) {
        if (!isAdmin) {
            $.toast({
                title: 'Warning!',
                showProgress: 'bottom',
                classProgress: 'blue',
                class: 'info',
                message: 'Permissions denied.',
                displayTime: 10000,
            });
            return true;
        } else {
            return false;
        }
    }

    function apiParams(action, params) {
        return {
            url: '/wp-json/bidspirit/v1/' + action,
            headers: {"X-WP-Nonce": ScoreSettings.nonce},
            type: 'POST',
            dataType: 'json',
            data: params
        }
    }

    document.addEventListener("DOMContentLoaded", function(event) {
        let bidspiritSessionId = bidspiritApi.getBidspiritSessionId(),
            reSyncActions = document.querySelectorAll('.re-sync-action'),
            clearIgnoreListActions = document.querySelectorAll('.clear-ignore-list-action'),
            singleLotReSync = document.getElementById('re-sync-single-lot'),
            fullLotReSync = document.getElementById('do-full-sync'),
            forceSync = document.getElementById('sync_force'),
            isAdmin = Boolean(parseInt(window.is_admin)),
            singleLotReSyncField = document.getElementById('re-sync-single-lot-field');

        if (reSyncActions.length > 0) {
            reSyncActions.forEach(function (action, index) {
                action.addEventListener('click', function (event) {
                    let $this = $(this),
                        //auctionId = this.getAttribute('data-action'),
                        params = this.getAttribute('data-params');

                    $this.prop('disabled', true);

                    $.ajax(
                        apiParams('status', {params})
                    )
                    .done(function(response) {
                        console.log(response, response.body.notificationType);

                        let auction = (response.body.auctionNumber) ? response.body.auctionNumber : response.body.auctionId;

                        let messaage = `Added auction '${auction}' to sync list. Please wait 5 minute and refresh this page.`;
                        if (response.body.notificationType === "AUCTION_CATALOG_UPDATED") {
                            messaage = `Lots of auction '${auction}' added to the sync list. Please wait 5 minute and refresh this page.`;
                        }
                        if (response.success) {
                            $.toast({
                                title: 'Success!',
                                showProgress: 'bottom',
                                classProgress: 'blue',
                                class: 'success',
                                message: messaage,
                                displayTime: 10000,
                            });
                        } else {
                            toastyError(window.bs_lang.not_found);
                        }
                        console.log("success");
                    })
                    .fail(function(response) {
                        console.log(response);
                        toastyError(loginMessage);
                    })
                    .always(function() {
                        $this.prop('disabled', false);
                        console.log("complete");
                    });
                });
            });
        }

        if (clearIgnoreListActions.length > 0) {
            clearIgnoreListActions.forEach(function (action, index) {
                action.addEventListener('click', function (event) {
                    let auctionId = this.getAttribute('data-auction');
                    $(event.target).prop("disabled", true);

                    $.ajax(apiParams('ignore-list', {
                        auction: auctionId
                    }))
                        .done(function(response) {
                            if (response.success) {
                                let tableElem = document.getElementById("exclude-item-" + response.auction);
                                if (!!tableElem) {
                                    setTimeout(function() {
                                        $(tableElem).fadeOut();
                                    }, 500);
                                }
                                $.toast({
                                    title: 'Success!',
                                    showProgress: 'bottom',
                                    classProgress: 'blue',
                                    class: 'success',
                                    message: 'Auction was removed from exclude list.',
                                    displayTime: 10000,
                                });
                            }
                        })
                        .fail(function(response) {
                            console.log(response);
                            toastyError(loginMessage);
                        })
                        .always(function() {
                            console.log("complete");
                            $(event.target).prop("disabled", false);
                        });
                })
            })
        }

        if (!!singleLotReSync && !!singleLotReSyncField) {
            singleLotReSync.addEventListener('click', function (event) {
                // https://qa.ruauctions.com/ui/lotPage/imperia-qa/source/catalog/auction/1333/lot/18217/long-name?lang=ru
                // https://housename.bidspirit.com/#catalog~276~304~21157
                let $this = $(this),
                    lotUrl = singleLotReSyncField.value,
                    reg = new RegExp(/#catalog~(\d+)~\d+~(\d+)$/),
                    reg2 = new RegExp(/\/catalog\/auction\/(\d+)\/lot\/(\d+)/),
                    res = lotUrl.match(reg),
                    res2 = lotUrl.match(reg2);

                $this.prop('disabled', true);
                if (!!res2 && res2[2] !== undefined) {
                    res = res2;
                }

                if (!!res && res[2] !== undefined) {
                    $.ajax(apiParams('item-info', {
                        lotId: res[2]
                    }))
                    .done(function(response) {
                        if (response.success === true) {
                            bidspiritApi.bidspiritQuery("items/getAuctionItem", {
                                sessionId: bidspiritSessionId,
                                auctionId: response.auctionId,
                                itemIndex: response.data.itemIndex,
                                language: response.lang
                            }, function (response2) {
                                $.ajax({
                                    url: "/wp-json/plugin/v1/sync-lot/",
                                    headers: {"X-WP-Nonce": ScoreSettings.nonce},
                                    type: "POST",
                                    dataType: "json",
                                    data: {
                                        item: response2.response.item,
                                        auctionId: response.auctionId,
                                        itemIndex: response.data.itemIndex,
                                        language: response.lang,
                                        sessionId: bidspiritSessionId
                                    }
                                }).done(function (response) {
                                    new Promise(function(resolve, reject) {
                                        let res = doSyncProcess('importData', () => {
                                            $this.prop('disabled', false)
                                        });
                                        resolve(res);
                                    }).then(function(result) {
                                        $.toast({
                                            title: 'Success!',
                                            showProgress: 'bottom',
                                            classProgress: 'blue',
                                            class: 'success',
                                            message: "Lot sync done.",
                                            displayTime: 10000,
                                        });
                                    })

                                })
                                .fail(function(response) {
                                    console.log(response);
                                    toastyError(loginMessage);
                                })
                                .always(function () {
                                    $this.prop('disabled', false);
                                });
                            });
                        } else {
                            toastyError(window.bs_lang.not_found);
                            $this.prop('disabled', false);
                        }
                    })
                    .fail(function(response) {
                        console.log(response);
                        toastyError(loginMessage);
                    })
                    .always(function() {
                        console.log("complete");
                    });
                } else {
                    $this.prop('disabled', false);
                    toastyError("Wrong URL. Please enter correct URL of the lot from Bidspirit system.");
                }
            });
        }

        if (!!fullLotReSync) {
            fullLotReSync.addEventListener('click', function (event) {
                let $this = $(this),
                    dimmer = $this.parents('.segment').find('.ui.dimmer');
                $this.prop('disabled', true);
                dimmer.addClass('active');

                new Promise(function(resolve, reject) {
                    resolve(1);
                }).then(function(result) {
                    return doSyncProcess('importBidSpiritUpcoming', () => {});
                }).then(function(result) {
                    console.log(result);
                    $.toast({
                        title: 'Step 1',
                        showProgress: 'bottom',
                        classProgress: 'blue',
                        class: 'success',
                        message: 'Upcoming auctions synced.',
                        displayTime: 10000,
                    });
                    return doSyncProcess('importBidSpiritPast', () => {});
                }).then(function(result) {
                    console.log(result);
                    $.toast({
                        title: 'Success!',
                        showProgress: 'bottom',
                        classProgress: 'blue',
                        class: 'success',
                        message: 'Resyncing auctions list. Please wait 5 minute and refresh this page.',
                        displayTime: 10000,
                    });

                    dimmer.removeClass('active');
                    return $this.prop('disabled', false);
                });
            });
        }

        if (!!forceSync) {
            forceSync.addEventListener('change', function (event) {
                $.ajax(apiParams('setting-update', {
                    option: event.target.name,
                    value: $(event.target).prop('checked')
                }))
                    .done(function(response) {
                        if (response.success) {
                            $.toast({
                                title: 'Success!',
                                showProgress: 'bottom',
                                classProgress: 'blue',
                                class: 'success',
                                message: 'Settings is updated.',
                                displayTime: 10000,
                            });
                        } else {
                            toastyError();
                        }

                        console.log("success");
                    })
                    .fail(function(response) {
                        console.log(response);
                        toastyError(loginMessage);
                    })
                    .always(function() {
                        console.log("complete");
                    });
            });
        }
    });
})(jQuery);
