$(function () {
    console.log("signalRJs Starts");
    
    window.RequestCount = 0;
    window.ConnectionId = "";
    /*window.CustomerId = 0;*/
    /*window.StoreId = 0;*/
    /*window.WorkingCurrency;*/
    /*window.IsAdmin = false;*/
    /*window.IsGuest = false;*/

    // AuctionStatus Enum
    window.AuctionStatus = Object.freeze({
        None: 0,
        Active: 1,
        FirstWarning: 2,
        SecondWarning: 4,
        Pause: 8,
        Sold: 16,
        NotSold: 32,
        TEST: 64
    });

    // HUF Formatter
    window.HUFFormatter = new Intl.NumberFormat("hu-HU", {
        style: "currency",
        currency: "HUF",
        minimumFractionDigits: 0,
        maximumFractionDigits: 0,
    });
    window.EURFormatter = new Intl.NumberFormat("eu-EU", {
        style: "currency",
        currency: "EUR",
    });

    // SignalR connection setup
    var connection = new signalR.HubConnectionBuilder()
        .withUrl("/auctionhub")
        .withServerTimeout(1200000)
        .withKeepAliveInterval(600000)
        .build();

    connection.on("send", messageWrapper => {
        MessageHandler.handle(messageWrapper);
    });

    connection.on("OnConnected", connId => {
	    window.ConnectionId = connId;
	    console.log("SignalR connected! connectionId: " + window.ConnectionId);
    });

    connection.on("OnDateTimeReceive", dateTime => {
	    console.log("SignalR date received! dateTime: " + dateTime);
    });

    function start() {
        connection.start().catch(function (err) {
            setTimeout(function () {
                start();
            }, 100000);
        });
    }

    connection.onclose(function () {
	    window.RequestCount = 0;
        start();
    });

    window.getRequestId = function() {
	    return window.ConnectionId + window.RequestCount;
    }

    // Global function to send a message to the server
    window.sendMessageToServer = function (messageType, senderId, messageWrapperData) {
	    window.RequestCount++;

	    var messageWrapper = {
		    MessageType: messageType,
		    SenderId: senderId,
		    RequestCount: window.RequestCount,
		    RequestId: window.getRequestId(),
		    Data: messageWrapperData
	    };

        console.log("Before send message to the server! " + messageType);

        connection.invoke("ReceiveMessageFromClient", messageWrapper)
            .then(() => {
                console.log("Message successfully sent to the server! " + messageType);
            })
            .catch(err => {
	            //window.RequestCount--;
                console.error("Error sending message to the server! " + messageType, err);
            });
    };

    start();
});
