@{
    ViewBag.Title = "Chat";
}
<h2>Chat</h2>

<style>
.discussion {
  color: black;
  font-family: monospace;
}
.notif {
  color: grey;
  font-family: monospace;
}
.pv {
  color: black;
  font-family: monospace;
  font-style: bold;
  background-color: yellow;
}

#targets { 
    display:inline-block;
}
</style>
<div class="container">
    <input type="hidden" id="displayname" />
   <div style="float:right; background-color: grey; padding:1em; margin:1em;">
    <h3>Salons</h3>
    <ul><li id="pubChan">Public</li></ul>
    <h3>Utilisateurs</h3>
    <ul id="userlist" style="list-style:none; padding: 1em; margin:1em;">
    </ul>

    </div>
    <ul id="discussion">
    </ul>
    <div id="targets">
        <div id="sendmessagebox">
     <input type="text" id="message" />
    <input type="button" id="sendmessage" value="@SR["Send"]" />
        </div>
    @if (ViewBag.IsAuthenticated) {
        <div id="sendpvbox">
            <input type="text" id="pv" />
            <button type="submit" id="sendpv">@SR["Send a private message"] @SR["to"] <div id="sendpvdest" /> </button>
        </div>
    }
    <input type="hidden" id="mySignalRConnectionIdHidden" value="" />
    </div>
</div>

@section scripts {
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/api/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script>
                
        $(function () {
            var pvuis;

            var setPrivate = function(li) 
            {
                $("#sendmessagebox").addClass("hidden");
                $("#sendpvbox").removeClass("hidden");
                pvuis = { CXs: $(li).data("cxids"), UserName: $(li).data("name")};
                $('#sendpvdest').html(pvuis.UserName)
                $('#pv').focus();
            }
            var setPublic = function()
            {
                $("#sendmessagebox").removeClass("hidden");
                $("#sendpvbox").addClass("hidden");
                $('#message').focus();
            }
            $('#pubChan').css('cursor','pointer');
            $('#pubChan').click(setPublic);
            setPublic();

            var getUsers = function() {
                console.log("Try and get user list ...");
                    $('#userlist').empty();
                    $('#to').empty();
                    $.get("/api/chat/users").done(
                        function(users) {
                            $.each(users, function () {
                                var user = this;
                                console.log(user);
                                var existent = $('#userlist li').filterByData("name",user.UserName);
                                if (existent.length>0) existent.remove();
                                var li = $('<li class="user"><img src="/Avatars/'+user.UserName+'.xs.png"> '+htmlEncode(user.UserName)+'</li>');
                                
                                var cxids = [];
                                $.each(user.Connections,function() {
                                    cxids.push(this.ConnectionId);
                                });
                                $(li).data("name",user.UserName);
                                $(li).data("cxids",cxids);
                                $(li).css('cursor','pointer');
                                $(li).click(function(){
                                    setPrivate(this);
                                });
                                li.appendTo('#userlist');
                            });
                        }
                    );
                };

            // Reference the auto-generated proxy for the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addMessage = function (name, message) {
                // Add the message to the page.
                $('#discussion').append('<li class="discussion"><strong>' + htmlEncode(name)
                    + '</strong>: ' + htmlEncode(message) + '</li>');
            };
            chat.client.addPV = function (name, message) {
                // Add the pv to the page.
                $('#discussion').append('<li class="pv"><strong>' + htmlEncode(name)
                    + '</strong>: ' + htmlEncode(message) + '</li>');
            };
            $.fn.filterByData = function(prop, val) {
                return this.filter(
                    function() { return $(this).data(prop)==val; }
                );
            }

            var onUserDisconnected = function (cxid, username) {
                 $('#userlist li').filter (function() { 
                     var nids = $(this).data("cxids").filter(function() { 
                         return $(this) !== cxid
                     });
                     if (nids.Length==0) $(this).remove();
                     else $(this).data("cxids",nids)
                     });
            };
            var onUserConnected =  function (cxid, username) {
                var connected = $('#userlist li').filterByData("name",username);
                if (connected.length>0) {
                    var ids = connected.data("cxids");
                    ids.push(cxid);
                    connected.data("cxids",ids);
                } else {
                    var li = $('<li class="user"><img src="/Avatars/'+username+'.xs.png"> '+username+'</li>');
                    li.data("name",username);
                    li.data("cxids",[cxid]);
                    li.appendTo('#userlist');
                    li.css('cursor','pointer');
                    li.click(function(){ setPrivate(this); });
                }
            };
            chat.client.notify = function (tag, message, data) {
                if (data) {
                // Add the pv to the page.
                
                if (tag === 'connected') {
onUserConnected(message, data);
$('#discussion').append('<li class="notif"><i>' + htmlEncode(tag)
                    + '</i> ' + htmlEncode(data) +'</li>');
                } 
                else if (tag === 'disconnected') 
                { 
                    onUserDisconnected(message, data);
$('#discussion').append('<li class="notif"><i>' + htmlEncode(tag)
                    + '</i> ' + htmlEncode(data) +'</li>');
                }
                else {
                    $('#discussion').append('<li class="notif"><i>' + htmlEncode(tag)
                    + '</i> ' + htmlEncode(message) + ' : ' + htmlEncode(data) + '</li>');
                }
                }
            };


            var sendMessage = function() {
                chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                $('#message').val('')
            };
            var sendPV = function () {
                    var msg = $('#pv').val();
                    // Call the Send method on the hub.
                    $.each(pvuis.CXs,function () { 
                        chat.server.sendPV( this, msg);
                     });
                     $('#discussion').append('<li class="pv">' + htmlEncode(pvuis.UserName)
                    + '<< ' + htmlEncode(msg) + '</li>');
                    // Clear text box and reset focus for next comment.
                    $('#pv').val('');
                }

            @if (!ViewBag.IsAuthenticated) {
            // Get the user name and store it to prepend to messages.
            <text>
            $('#displayname').val(prompt('Enter your name:', ''));
            </text>
            }


            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    sendMessage().focus();
                });
                $( "#message" ).keydown(function( event ) {
                    if ( event.which == 13 ) {
                        sendMessage()
                        }
                });
                $( "#pv" ).keydown(function( event ) {
                    if ( event.which == 13 ) {
                        sendPV()
                        }
                });
                $('#sendpv').click(function () {
                    // Call the Send method on the hub.
                    sendPV().focus();
                });
                
                getUsers();
            });

            $("#btnDebug").click(getUsers);
            $.connection.hub.disconnected(function () { 
                setTimeout(function () {
                    $.connection.hub.start().done(function () {
                        $("#mySignalRConnectionIdHidden").val($.connection.hub.id);
                    }, 3000); // Re-start connection after 3 seconds
                    }); 
            });
            $( window ).unload(function() { chat.server.abort(); }); 
        });
        // This optional function html-encodes messages for display in the page.
        
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }

    </script>
}
