window.sendBidMessage = function (ptaId, auctionId, bidPrice, productId) {

    setBidButtonDisabledById("signalRBidButton" + ptaId, true);

    var bidMessage = {
        ProductAuctionMappingId: ptaId,
        AuctionId: auctionId,
        BidPrice: bidPrice,
        ProductId: productId,
        CustomerId: window.CustomerId
    };

    var content = JSON.stringify(bidMessage);
    console.log("WTF " + content);
    sendMessageToServer("BidRequestMessage", window.CustomerId, content);

    return false;
}



window.setBidButtonDisabledById = function (bidButtonElementId, disabled, updateDisabledState = true) {
    if (!updateDisabledState) return;

    setBidButtonDisabled(document.getElementById(bidButtonElementId), disabled, updateDisabledState);
}

window.sendAuctionStatusChange = function (ptaId, auctionStatus) {
    var customerId = window.CustomerId;
    console.log("Send auctionstatus: " + customerId + ", " + ptaId);
    // Create the message object
    var auctionMessage = {
        ProductToAuctionId: ptaId,
        AuctionStatus: auctionStatus
    };

    // Convert to JSON and log
    var content = JSON.stringify(auctionMessage);
    console.log(content);

    // Send the message via SignalR
    sendMessageToServer("AuctionProductStatusRequest", customerId, content);

    return false;
}


window.refreshPublicBidBox = function (bidNotification, updateBidButtonDisabledState, ptaId, thisPta) {

    //now we are refreshing any widget that has this ptaId

    var auctionDto = bidNotification.auctionDto;
    
    /*var productAuctionMappingId = ptaId;*/
    var winnerId = thisPta.winnerCustomerId;
    var isMyBid;

    console.log("productId: " + thisPta.productId);
    var widgetPriceElement = document.getElementById("price-value-" + thisPta.productId);
    //var widgetPriceElement = $("#price-value-" + productToAuction.productId);

    
    var widgetPriceElementInList = $('.product-item[data-productid="' + thisPta.productId + '"]');
    console.log("WidgetPriceElement" + widgetPriceElement);
    var currency = window.WorkingCurrency;
    console.log(currency);

    var bidButtonElement = document.getElementById("signalRBidButton" + ptaId);
    var bidButtonElementText = document.getElementById("signalRBidButtonText" + ptaId);
    var storedBidPricePlaceholder = document.getElementById("bidPriceContainer" + ptaId);
    var licitStepElement = document.getElementById("licitStepText" + ptaId);
    var bidBox = document.getElementById("publicProductBidBox" + ptaId);
    var bidBoxTitle = document.getElementById("bidBoxTitle" + ptaId);
    console.log("signalRBidButton" + ptaId);
    console.log(bidButtonElement);
    console.log(storedBidPricePlaceholder);
    console.log(licitStepElement);
    console.log(bidBox);
    console.log(bidBoxTitle);
    console.log(bidNotification);

    if (winnerId == window.CustomerId) {
        isMyBid = true;

    }

    console.log("ProductToAuctionId: " + ptaId);

    //TODO: TESZT STATUS!!! - JTEST.
    var status = thisPta.auctionStatus;
    //var status = AuctionStatus.TEST;


    if (updateBidButtonDisabledState) {
        setButtons(status, ptaId);
    }


    if (widgetPriceElement || widgetPriceElementInList) {

        if (widgetPriceElement) {
            console.log("PRICE: " + bidNotification.currentPrice);
            /*if (productAuctionMappingId == ptaId) {*/
            console.log("THIS IS FOR US! SORRY FOR SHOUTING");
            if (currency.CurrencyCode == "EUR") {
                console.log("EUR");
                widgetPriceElement.textContent = EURFormatter.format(bidNotification.currentPrice * window.WorkingCurrency.Rate); // Update the price
                //licitStepElement.textContent = EURFormatter.format(bidNotification.nextStepAmount * window.WorkingCurrency.Rate);
            }
            else {
                
                widgetPriceElement.textContent = HUFFormatter.format(bidNotification.currentPrice); // Update the price
                //widgetPriceElement.setAttribute("id", "hugrabug");
                //licitStepElement.textContent = HUFFormatter.format(bidNotification.nextStepAmount);
            }
            /*}*/
        }
        else if (widgetPriceElementInList) {
            console.log("PRICE: " + bidNotification.currentPrice);
            var widgetPriceElements = widgetPriceElementInList.find('.actual-price');
            /*if (productAuctionMappingId == ptaId) {*/
            console.log("THIS IS FOR US! SORRY FOR SHOUTING");
            if (widgetPriceElements && widgetPriceElements.length > 0) {
                if (currency.CurrencyCode == "EUR") {
                    console.log("EUR");
                    widgetPriceElements[0].textContent = EURFormatter.format(bidNotification.currentPrice * window.WorkingCurrency.Rate); // Update the price
                    //licitStepElement.textContent = EURFormatter.format(bidNotification.nextStepAmount * window.WorkingCurrency.Rate);
                }
                else {
                    
                    widgetPriceElements[0].textContent = HUFFormatter.format(bidNotification.currentPrice); // Update the price                    
                    //licitStepElement.textContent = HUFFormatter.format(bidNotification.nextStepAmount);
                }
            }
            /*}*/
        }

        /*if (productAuctionMappingId == ptaId) {*/
        /*console.log("THIS IS FOR US! SORRY FOR SHOUTING");*/
        if (currency.CurrencyCode == "EUR") {
            console.log("EUR");
            //widgetPriceElement.textContent = EURFormatter.format(bidNotification.currentPrice * window.WorkingCurrency.Rate); // Update the price
            licitStepElement.textContent = EURFormatter.format(bidNotification.nextStepAmount * window.WorkingCurrency.Rate);
        }
        else {
            console.log("HUF");
            //widgetPriceElement.textContent = HUFFormatter.format(bidNotification.currentPrice); // Update the price
            licitStepElement.textContent = HUFFormatter.format(bidNotification.nextStepAmount);
        }

        storedBidPricePlaceholder.value = Number(bidNotification.nextBidPrice);
        setBidButtonDisabled(bidButtonElement, !thisPta.isActiveItem, updateBidButtonDisabledState);

        var list;
        if (isMyBid) {
            console.log("This is my bid");
            list = bidBox.classList;
            //list.add("bg-success");
            //list.remove("bg-primary");

            bidButtonElementText.textContent = window.LocalizationStrings.GoodJob;
            bidBoxTitle.textContent = thisPta.auctionStatus == AuctionStatus.Sold ? window.LocalizationStrings.YouWin : window.LocalizationStrings.YourBidLeading;

            if (window.IsAdmin) {
                console.log("I AM WEASEL!!! " + window.IsAdmin);
                setBidButtonDisabled(bidButtonElement, !thisPta.isActiveItem, updateBidButtonDisabledState);
            } else {
                console.log("I AM NOT WEASEL!!! " + window.IsAdmin);
                setBidButtonDisabled(bidButtonElement, true, updateBidButtonDisabledState);
            }
        } else {
            list = bidBox.classList;
            //list.add("bg-primary");
            //list.remove("bg-success");
            bidBoxTitle.textContent = thisPta.auctionStatus == AuctionStatus.Sold ? window.LocalizationStrings.Sold : window.LocalizationStrings.PlaceABid;

            if (currency.CurrencyCode == "EUR") {
                bidButtonElementText.textContent = EURFormatter.format(bidNotification.nextBidPrice * window.WorkingCurrency.Rate);
                //bidButtonElement.textContent = EURFormatter.format(storedBidPricePlaceholder.value);
            } else {
                bidButtonElementText.textContent = HUFFormatter.format(bidNotification.nextBidPrice);
                //bidButtonElement.textContent = HUFFormatter.format(storedBidPricePlaceholder.value);
            }
            bidButtonElement.disabled = false;
        }
        //console.log(widgetPriceElement.textContent);
        console.log(`WidgetPrice updated to: ${bidNotification.currentPrice}`);
        

        //} else {
        //	console.log("Not for this product");
        //}
    } else {
        console.warn("Element with ID 'WidgetPrice' not found in the DOM.");
    }
}

function setButtons(auctionStatus, ptaId) {
    console.log("SetButtons called: " + auctionStatus);

    // Button IDs and their default states for each AuctionStatus
    //true = disabled
    var buttonStates = {
        [AuctionStatus.None]: {
            signalRBidButton: true,
            signalRFirstWarningButton: true,
            signalRSecondWarningButton: true,
            signalROpenItemButton: false,
            signalRCloseItemButton: true,
            signalRPauseItemButton: true,
            signalRRevertBidButton: true,
            signalRResetItemButton: true,
        },
        [AuctionStatus.Active]: {
            signalRBidButton: false,
            signalRFirstWarningButton: false,
            signalRSecondWarningButton: true,
            signalROpenItemButton: true,
            signalRCloseItemButton: true,
            signalRPauseItemButton: false,
            signalRRevertBidButton: true,
            signalRResetItemButton: true,
        },
        [AuctionStatus.FirstWarning]: {
            signalRBidButton: false,
            signalRFirstWarningButton: true,
            signalRSecondWarningButton: false,
            signalROpenItemButton: true,
            signalRCloseItemButton: true,
            signalRPauseItemButton: false,
            signalRRevertBidButton: true,
            signalRResetItemButton: true,
        },
        [AuctionStatus.SecondWarning]: {
            signalRBidButton: false,
            signalRFirstWarningButton: true,
            signalRSecondWarningButton: true,
            signalROpenItemButton: true,
            signalRCloseItemButton: false,
            signalRPauseItemButton: false,
            signalRRevertBidButton: true,
            signalRResetItemButton: true,
        },
        [AuctionStatus.Pause]: {
            signalRBidButton: true,
            signalRFirstWarningButton: true,
            signalRSecondWarningButton: true,
            signalROpenItemButton: false,
            signalRCloseItemButton: true,
            signalRPauseItemButton: true,
            signalRRevertBidButton: false,
            signalRResetItemButton: false,
        },
        [AuctionStatus.Sold]: {
            signalRBidButton: true,
            signalRFirstWarningButton: true,
            signalRSecondWarningButton: true,
            signalROpenItemButton: true,
            signalRCloseItemButton: true,
            signalRPauseItemButton: true,
            signalRRevertBidButton: true,
            signalRResetItemButton: true,
        },
        [AuctionStatus.NotSold]: {
            signalRBidButton: true,
            signalRFirstWarningButton: true,
            signalRSecondWarningButton: true,
            signalROpenItemButton: true,
            signalRCloseItemButton: true,
            signalRPauseItemButton: true,
            signalRRevertBidButton: true,
            signalRResetItemButton: true,
        },
        [AuctionStatus.TEST]: {
            signalRBidButton: false,
            signalRFirstWarningButton: false,
            signalRSecondWarningButton: false,
            signalROpenItemButton: false,
            signalRCloseItemButton: false,
            signalRPauseItemButton: false,
            signalRRevertBidButton: false,
            signalRResetItemButton: false,
        },

    };

    // Get the states for the given auctionStatus
    var states = buttonStates[auctionStatus];
    if (!states) {
        console.error("Unknown AuctionStatus: ", auctionStatus);
        return;
    }

    // Apply the states to each button
    Object.keys(states).forEach((buttonId) => {
        var button = document.getElementById(buttonId + ptaId);
        if (button) {
            button.disabled = states[buttonId];
            button.hidden = states[buttonId];
        } else {
            console.warn(`Button with ID ${buttonId} not found.`);
        }
    });
}


function handleAuctionUpdate(auctionStatusNotification, myPtaId) {
    var ids = auctionStatusNotification.auctionDto.productToAuctionDtos.map(pta => pta.id);
    ids.forEach(ptaId => {
        console.log(ptaId);
        var productToAuctionDtos = auctionStatusNotification.auctionDto.productToAuctionDtos;

        // Find the object with the matching Id
        var matchingDto = productToAuctionDtos.find(pta => pta.id === ptaId);

        if (matchingDto) {
            console.log('Matching ProductToAuctionDto:', matchingDto);
            UpdateBox(ptaId, matchingDto.productId, auctionStatusNotification.auctionDto, matchingDto);
        } else {
            console.log(`No ProductToAuctionDto found with Id: ${ptaId}`);
        }
    });

}

function UpdateBox(ptaId, productId, auctionDto, ptaDto) {
    var widgetPriceElement = document.getElementById("price-value-" + productId);
    var widgetPriceElementInList = $('.product-item[data-productid="' + productId + '"]');
    var bidButtonElement = document.getElementById("signalRBidButton" + ptaId);
    var licitStepElement = document.getElementById("licitStepText" + ptaId);
    var bidBoxTitle = document.getElementById("bidBoxTitle" + ptaId);

    var productAuctionMappingId = ptaId;
    let isMyBid = false;

    //TODO: TESZT STATUS!!! - JTEST.
    let itemStatus = ptaDto.auctionStatus;
    //var itemStatus = AuctionStatus.TEST;
    let winnerId = ptaDto.winnerCustomerId;
    if (winnerId == window.CustomerId) {
        isMyBid = true;

    }
    console.log("handle auction update called" + productAuctionMappingId);
    console.log("auction status:" + itemStatus);
    if (widgetPriceElement || widgetPriceElementInList) {

        /*if (productAuctionMappingId == bidBoxPageViewModel.ProductToAuctionId) {*/
        console.log("THIS IS FOR US! SORRY FOR SHOUTING");
        switch (itemStatus) {
            case AuctionStatus.None:
                location.reload();
                break;

            case AuctionStatus.Active:
                if (isMyBid) {
                    bidBoxTitle.textContent = window.LocalizationStrings.YourBidLeading;
                } else {
                    bidBoxTitle.textContent = window.LocalizationStrings.PlaceABid;
                }
                break;

            case AuctionStatus.Pause:
                bidBoxTitle.textContent = window.LocalizationStrings.AuctionPaused;
                break;

            case AuctionStatus.FirstWarning:
                bidBoxTitle.textContent = window.LocalizationStrings.FirstWarning;
                break;

            case AuctionStatus.SecondWarning:
                bidBoxTitle.textContent = window.LocalizationStrings.SecondWarning;
                break;

            case AuctionStatus.Sold:
                if (isMyBid) {
                    bidBoxTitle.textContent = window.LocalizationStrings.YouWin;
                } else {
                    bidBoxTitle.textContent = window.LocalizationStrings.ItemClosed;
                }
                break;

            case AuctionStatus.NotSold:
                bidBoxTitle.textContent = window.LocalizationStrings.ItemClosed;
                break;

            default:
                console.warn("Unknown AuctionStatus: ", itemStatus);
        }


        /*console.log(`Status updated to: ${auctionStatusNotification.currentPrice}, next bid is ${bidBoxPageViewModel.NextBidPrice}`);*/
        
        //}

        //else {
        //	console.log("Not for this product");
        //}


    } else {
        console.warn("Element with ID 'WidgetPrice' not found in the DOM.");
    }
    setButtons(itemStatus, ptaId);

}



