@using Nop.Plugin.Misc.AuctionPlugin.Domains.Enums
@using Nop.Web.Framework.TagHelpers.Shared
@using System.Globalization
@model ProductBidBoxViewModel
@* @inject IJsonHelper JsonHelper; *@

@* @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(myObj) as String) *@

<style>
    .old-product-price {
        text-decoration: unset !important;
    }
</style>

@{
    if (!Model.IsGuest)
    {
        if (Model.FirstProductToAuction != null)
        {

            var bgClass = Model.FirstProductToAuction.WinnerCustomerId == Model.CustomerId ? "bg-success" : "bg-primary";
            var bidButtonActive = Model.IsItemActive && (Model.FirstProductToAuction.WinnerCustomerId != Model.CustomerId || Model.IsAdmin);
            var auctionStatus = Model.FirstProductToAuction.AuctionStatus;
            var lastBidIsMine = Model.FirstProductToAuction.WinnerCustomerId == Model.CustomerId;


            var title = auctionStatus switch
            {
                AuctionStatus.Sold => lastBidIsMine ? @T("Plugins.Misc.AuctionPlugin.YouWin") : @T("Plugins.Misc.AuctionPlugin.Sold"),
                AuctionStatus.NotSold => @T("Plugins.Misc.AuctionPlugin.Finished"),
                _ => lastBidIsMine ? @T("Plugins.Misc.AuctionPlugin.YourBidLeading") : @T("Plugins.Misc.AuctionPlugin.PlaceABid")
            };

            if (Model.WidgetZone.Equals(PublicWidgetZones.ProductDetailsOverviewTop))
            {
                
                        <div class="d-flex justify-content-between" id="otherAuctionItems">
                            <a href="@(string.IsNullOrEmpty(Model.LastProductUrl) ? "#" : Model.LastProductUrl)" @(string.IsNullOrEmpty(Model.LastProductUrl) ? "disabled" : string.Empty)>
                                <div class="card mb-3" style="max-width: 540px;">
                                    <div class="row g-0">
                                        @*<div class="col-md-4">
                <img src="@(string.IsNullOrEmpty(Model.LastProductImageUrl) ? "https://placehold.co/400" : Model.LastProductImageUrl)" class="img-fluid rounded-start" alt="...">
                </div>
                <div class="col-md-8">*@
                                        <div class="col-12">
                                            <div class="card-body">
                                                <h5 class="card-title">@(string.IsNullOrEmpty(Model.LastProductUrl) ? @T("Plugins.Misc.AuctionPlugin.StartOfList") : @T("Plugins.Misc.AuctionPlugin.BackToLast"))</h5>
                                                <p class="card-text">@(string.IsNullOrEmpty(Model.LastProductName) ? "---" : Model.LastProductName)</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </a>

                            <a href="@(string.IsNullOrEmpty(Model.NextProductUrl) ? "#" : Model.NextProductUrl)" @(string.IsNullOrEmpty(Model.NextProductUrl) ? "disabled" : string.Empty)>
                                <div class="card mb-3" style="max-width: 540px;">
                                    <div class="row g-0">
                                        @*<div class="col-md-4">
                <img src="@(string.IsNullOrEmpty(Model.NextProductImageUrl) ? "https://placehold.co/400" : Model.NextProductImageUrl)" class="img-fluid rounded-start" alt="...">
                </div>
                <div class="col-md-8">*@
                                        <div class="col-12">
                                            <div class="card-body">
                                                <h5 class="card-title">@(string.IsNullOrEmpty(Model.NextProductUrl) ? @T("Plugins.Misc.AuctionPlugin.EndOfList") : @T("Plugins.Misc.AuctionPlugin.ComingUp"))</h5>
                                                <p class="card-text">@(string.IsNullOrEmpty(Model.NextProductName) ? "---" : Model.NextProductName)</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </a>

                        </div>
            }


                    <div id="publicProductBidBox@(Model.ProductToAuctionId)" class="p-3 @bgClass text-white">
                    <input id="bidPriceContainer@(Model.ProductToAuctionId)" value="@Model.NextBidPrice" hidden/>
                        <div class="row">
                            <div class="col-3"><strong>#@Model.AuctionDto.ProductToAuctionDtos.FirstOrDefault()!.SortIndex</strong></div>
                            <div class="col-9"><a target="_blank" class="btn btn-secondary btn-sm float-end" href="https://youtube.com/live/6yfnmyQE7Uw?feature=share"><i class="fa-brands fa-youtube"></i> Youtube live</a></div>
                        </div>

                        <h4 id="bidBoxTitle@(Model.ProductToAuctionId)">@title</h4>
                        <div class="row justify-content-between">
                            @*<div class="col-xs-12 col-md-6 col-lg-4">
                                <strong>Base Price:</strong>
                                @{
                            if (Model.WorkingCurrency.CurrencyCode == "EUR")
                            {

                                                <span class="value">@($"{((decimal)Model.BasePriceInWorkingCurrency).ToString("C", new CultureInfo("de-DE"))}")</span>
                            }
                            else
                            {
                                                <span class="value">@($"{((decimal)Model.BasePrice).ToString("C", new CultureInfo("hu-HU"))}")</span>

                            }
                                }

                            </div>*@
                            <div class="col-xs-12 col-md-6 col-lg-4">
                                <strong>Bid Step:</strong>
                                @{
                            if (Model.WorkingCurrency.CurrencyCode == "EUR")
                            {
                                                <span id="licitStepText@(Model.ProductToAuctionId)" class="value">@($"{Model.LicitStepInWorkingCurrency.ToString("C", new CultureInfo("de-DE"))}")</span>

                            }
                            else
                            {
                                // <span id="licitStepText" class="value">@($"{Model.LicitStep:c}")</span>
                                                <span id="licitStepText@(Model.ProductToAuctionId)" class="value">@($"{Model.LicitStep.ToString("C", new CultureInfo("hu-HU"))}")</span>
                            }
                                }

                            </div>
                <div class="col-xs-12 col-md-6 col-lg-4">
                            <button id="signalRBidButton@(Model.ProductToAuctionId)" class="btn btn-success float-end" style="text-transform: uppercase;" type="button" @(!bidButtonActive ? "disabled" : string.Empty)>
                                    @{
                                if (Model.WorkingCurrency.CurrencyCode == "EUR")
                                {
                                                    @T("Plugins.Misc.AuctionPlugin.BidButtonPrefix") @($"{Model.NextBidPriceInWorkingCurrency.ToString("C", new CultureInfo("de-DE"))}")

                                }
                                else
                                {
                                    // <span id="licitStepText" class="value">@($"{Model.LicitStep:c}")</span>

                                                    @T("Plugins.Misc.AuctionPlugin.BidButtonPrefix") @($"{Model.NextBidPrice.ToString("C", new CultureInfo("hu-HU"))}")
                                }
                                    }





                                </button>
                                @* <button id="bidButton" class="btn btn-success">

            Bid @String.Format("{0:c}", Model.NextBidPrice)
            </button> *@
                            </div>
                        </div>


                        @* <button id="testButton" class="btn btn-success">
    TestButton
    </button> *@

                        <div id="bidFeedback" class="mt-3"></div>
                    </div>


            if (Model.IsAdmin)
            {
                        <div id="publicProductBidBoxAdmin@(Model.ProductToAuctionId)" class="p-3 bg-secondary text-white">
                            <h4>Manage auction!</h4>
                            <div id="bidBoxAdminButtons@(Model.ProductToAuctionId)" class="d-flex justify-content-between mb-3">


                                <div>
                                    <button id="signalROpenItemButton@(Model.ProductToAuctionId)" class="btn btn-primary" style="text-transform: uppercase;" type="button" @(Model.AuctionStatus == AuctionStatus.None || Model.AuctionStatus == AuctionStatus.Pause ? string.Empty : "disabled hidden")>
                                        Open item
                                    </button>
                                    <button id="signalRPauseItemButton@(Model.ProductToAuctionId)" class="btn btn-warning" style="text-transform: uppercase;" type="button" @(Model.AuctionStatus == AuctionStatus.Active || Model.AuctionStatus == AuctionStatus.FirstWarning || Model.AuctionStatus == AuctionStatus.SecondWarning ? string.Empty : "disabled hidden")>
                                        Pause auction
                                    </button>
                                    <button id="signalRRevertBidButton@(Model.ProductToAuctionId)" class="btn btn-warning" style="text-transform: uppercase;" type="button" @(Model.AuctionStatus != AuctionStatus.Pause ? "disabled hidden" : string.Empty)>
                                        Revert bid
                                    </button>
                                    <button id="signalRResetItemButton@(Model.ProductToAuctionId)" class="btn btn-danger" style="text-transform: uppercase;" type="button" @(Model.AuctionStatus != AuctionStatus.Pause ? "disabled hidden" : string.Empty)>
                                        Reset auction
                                    </button>
                                </div>
                                <div>
                                    <button id="signalRFirstWarningButton@(Model.ProductToAuctionId)" class="btn btn-warning" style="text-transform: uppercase;" type="button" @(Model.AuctionStatus != AuctionStatus.Active ? "disabled hidden" : string.Empty)>
                                        First warning
                                    </button>
                                    <button id="signalRSecondWarningButton@(Model.ProductToAuctionId)" class="btn btn-danger" style="text-transform: uppercase;" type="button" @(Model.AuctionStatus != AuctionStatus.FirstWarning ? "disabled hidden" : string.Empty)>
                                        Second warning
                                    </button>
                                    <button id="signalRCloseItemButton@(Model.ProductToAuctionId)" class="btn btn-success" style="text-transform: uppercase;" type="button" @(Model.AuctionStatus != AuctionStatus.SecondWarning ? "disabled hidden" : string.Empty)>
                                        Finished
                                    </button>
                                </div>


                            </div>
                        </div>
            }
            else
            {
                // <p>No access to admin level buttons</p>
            }
        }
    }
    else
    {
                <div id="publicProductBidBoxGuest@(Model.ProductToAuctionId)" class="p-3 bg-primary text-white">
                    <h4>This item is under auction!</h4>
                    <div id="bidBoxGuestMessage@(Model.ProductToAuctionId)" class="d-flex justify-content-between mb-3">

                        <p>@T("Plugins.Misc.AuctionPlugin.PleaseLogInOrRegister")</p>
                    </div>
                </div>
    }
}

<script>
    var bidBoxPageViewModel;
    //var bidPrice;
    $(window).load(function () {
        try {

            bidBoxPageViewModel = @Html.Raw(Json.Serialize(Model));
        }
        catch (e) {
            console.log(e); // Logs the error
        }
        console.log("bidBoxPageViewModel " + bidBoxPageViewModel);
        console.log(bidBoxPageViewModel.WidgetZone);
        //console.log(typeof sendMessageToServer);
        document.getElementById("bidPriceContainer" + bidBoxPageViewModel.ProductToAuctionId).value = bidBoxPageViewModel.NextBidPrice;
        setOnClicks(bidBoxPageViewModel.ProductToAuctionId, bidBoxPageViewModel);
            //var status = bidBoxPageViewModel.productToAuctionDto.auctionStatus;
            //setButtons(status);
    });    

    function setOnClicks(ptaId, viewModel) {

        console.log("Setting onclick methods");
        $("#signalRBidButton" + ptaId).on("click", function () {
            event.preventDefault();
            var storedBidPrice = document.getElementById("bidPriceContainer" + ptaId).value;
            sendBidMessage(ptaId,
                viewModel.AuctionId,
                storedBidPrice,
                viewModel.ProductId                                
            );
        });

        $("#signalROpenItemButton" + ptaId).on("click", function () {

            this.disabled = true;
            event.preventDefault();

            sendAuctionStatusChange(ptaId, AuctionStatus.Active);

            return false;
        });
        $("#signalRCloseItemButton" + ptaId).on("click", function () {

            this.disabled = true;
            event.preventDefault();

            sendAuctionStatusChange(ptaId, AuctionStatus.Sold);

            return false;
        });
        $("#signalRFirstWarningButton" + ptaId).on("click", function () {

            this.disabled = true;
            event.preventDefault();

            sendAuctionStatusChange(ptaId, AuctionStatus.FirstWarning);

            return false;
        });
        $("#signalRSecondWarningButton" + ptaId).on("click", function () {

            this.disabled = true;
            event.preventDefault();

            sendAuctionStatusChange(ptaId, AuctionStatus.SecondWarning);

            return false;
        });
        $("#signalRPauseItemButton" + ptaId).on("click", function () {

            this.disabled = true;
            event.preventDefault();

            sendAuctionStatusChange(ptaId, AuctionStatus.Pause);

            return false;
        });
        $("#signalRRevertBidButton" + ptaId).on("click", function () {

            this.disabled = true;
            event.preventDefault();

            if (!bidBoxPageViewModel) {
                console.log("we need viewmodel data");
                bidBoxPageViewModel = viewModel;
            }

            var revertMessage = {
                ProductToAuctionId: bidBoxPageViewModel.ProductToAuctionId
            };

            var content = JSON.stringify(revertMessage);
            console.log("WTF " + content);
            sendMessageToServer("RevertAuctionBidRequest", bidBoxPageViewModel.CustomerId, content);

            return false;
        });
        $("#signalRResetItemButton" + ptaId).on("click", function () {

            this.disabled = true;
            event.preventDefault();

            sendAuctionStatusChange(AuctionStatus.None);

            return false;
        });
    }

    // function SendRevertAuctionBidRequest() {

    //     var revertButtonElement = document.getElementById("signalRRevertBidButton");
    //     revertButtonElement.disabled = true;
    //     sendMessageToServer("RevertAuctionBidRequest", bidBoxPageViewModel.ProductToAuctionId);
    // }

    

    function setBidButtonDisabled(bidButtonElement, disabled, updateDisabledState = true) {
        if (!updateDisabledState) return;

        setElementDisabled(bidButtonElement, disabled, updateDisabledState);
    }

    function setElementDisabledById(domElementId, disabled) {
        setElementDisabled(document.getElementById(domElementId), disabled);
    }

    function setElementDisabled(domElement, disabled) {
        if (!domElement)
            return;

        domElement.disabled = disabled;
    }

    
    
</script>