{% load static %}
<!DOCTYPE html>
<html>

<head>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600,700,300' rel='stylesheet' type='text/css'>
    <script src="https://use.typekit.net/hoy3lrg.js"></script>
    <script>
        try {
            Typekit.load({
                async: true
            });
        } catch (e) {}
    </script>
    <link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css'>
    <link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.2/css/font-awesome.min.css'>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <!-- <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script> -->
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <link rel="stylesheet" href="{% static 'css/style.css' %}" />
</head>

<body>
    <div id="frame">
        <div id="sidepanel">
            <div id="profile">
                <div class="wrap">
                    <img id="profile-img" src="http://emilcarlsson.se/assets/mikeross.png" class="online" alt="" />
                    <p>{{request.user.username}}</p>
                    <i class="fa fa-chevron-down expand-button" aria-hidden="true"></i>
                    <div id="status-options">
                        <ul>
                            <li id="status-online" class="active"><span class="status-circle"></span>
                                <p>Online</p>
                            </li>
                            <li id="status-away"><span class="status-circle"></span>
                                <p>Away</p>
                            </li>
                            <li id="status-busy"><span class="status-circle"></span>
                                <p>Busy</p>
                            </li>
                            <li id="status-offline"><span class="status-circle"></span>
                                <p>Offline</p>
                            </li>
                        </ul>
                    </div>
                    <div id="expanded">
                        <label for="twitter"><i class="fa fa-facebook fa-fw" aria-hidden="true"></i></label>
                        <input name="twitter" type="text" value="mikeross" />
                        <label for="twitter"><i class="fa fa-twitter fa-fw" aria-hidden="true"></i></label>
                        <input name="twitter" type="text" value="ross81" />
                        <label for="twitter"><i class="fa fa-instagram fa-fw" aria-hidden="true"></i></label>
                        <input name="twitter" type="text" value="mike.ross" />
                    </div>
                </div>
            </div>
            <div id="search">
                <label for=""><i class="fa fa-search" aria-hidden="true"></i></label>
                <input type="text" placeholder="Search contacts..." />
            </div>
            <div id="contacts">
                <ul>
                    {% for dialog_user in dialog_users %}
                    <a href="{% url 'chatter:room' %}?opponent={{dialog_user.username}}">
                        <li class="contact {% if dialog_user.username == opponent_username %}active{% endif %}">
                            <div class="wrap">
                                <span class="contact-status online"></span>
                                <img src="http://emilcarlsson.se/assets/louislitt.png" alt="" />
                                <div class="meta">
                                    <p class="name">{{dialog_user.username}}</p>
                                    <p class="preview">You just got LITT up, Mike.</p>
                                </div>
                            </div>
                        </li>
                    </a>
                    {% endfor %}
                </ul>
            </div>
            <div id="bottom-bar">
                <button id="addcontact"><i class="fa fa-user-plus fa-fw" aria-hidden="true"></i> <span>Add contact</span></button>
                <button id="settings"><i class="fa fa-cog fa-fw" aria-hidden="true"></i> <span>Settings</span></button>
            </div>
        </div>
        <div class="content">
            <div class="contact-profile">
                <img src="http://emilcarlsson.se/assets/harveyspecter.png" alt="" />
                <p>{{ opponent_username }}</p>
                <div class="social-media">
                    <i class="fa fa-facebook" aria-hidden="true"></i>
                    <i class="fa fa-twitter" aria-hidden="true"></i>
                    <i class="fa fa-instagram" aria-hidden="true"></i>
                </div>
            </div>
            <div class="messages">
                <button data-page="1" id="loadmore" class="btn d-flex mx-auto">load more</button>
                <ul id="chat-log">
                    <!-- {% comment %} -->
                    <li class="sent">
                        <img src="http://emilcarlsson.se/assets/mikeross.png" alt="" />
                        <p>How the hell am I supposed to get a jury to believe you when I am not even sure that I do?!</p>
                    </li>

                    <li class="replies">
                        <img src="http://emilcarlsson.se/assets/harveyspecter.png" alt="" />
                        <p>When you're backed against the wall, break the god damn thing down.</p>
                    </li>
                    <!-- {% endcomment %} -->

                </ul>
            </div>
            <div class="message-input">
                <div class="wrap">
                    <input id="chat-message-input" type="text" placeholder="Write your message..." />
                    <i class="fa fa-paperclip attachment" aria-hidden="true"></i>
                    <button id="chat-message-submit" class="submit">
          <i class="fa fa-paper-plane" aria-hidden="true"></i>
        </button>
                </div>
            </div>
        </div>
    </div>
    <script>
        var ROOM_URL = '{% url "chatter:room" %}'
        var CSRF_TOKEN = '{{ csrf_token }}'
    </script>
    <script src="{% static 'js/main.js' %}"></script>
    <script src="{% static 'js/reconnectwebsockets.min.js' %}"></script>
    <script type="text/javascript">
        var roomPk = JSON.parse('{{room_pk_json|safe}}');
        var username = JSON.parse('{{username|safe}}');
        var opponent_username = '{{ opponent_username }}'

        var chatSocket = new ReconnectingWebSocket(
            'ws://' + window.location.host +
            '/ws/chat/' + roomPk + '/');

        chatSocket.onopen = function(e) {
            // fetchMessages(); 
            // fetch history
            console.log('connected')
        }

        chatSocket.onmessage = function(e) {
            // var data = JSON.parse(e.data);   
            // if (data['command'] === 'messages') {
            //     for (let i = 0; i < data['messages'].length; i++) {
            //         createMessage(data['messages'][i]);
            //     }
            // } else if (data['command'] === 'new_message') {
            //     createMessage(data['message']);
            // }
            const data = JSON.parse(e.data);
            console.log(data)

            createMessage(data)
                // document.querySelector('#chat-log').value += (data.message + '\n');
                // console.log(data)
        };

        chatSocket.onclose = function(e) {
            console.error('Chat socket closed unexpectedly');
        };

        document.querySelector('#chat-message-input').onkeyup = function(e) {
            if (e.keyCode === 13) { // enter, return
                document.querySelector('#chat-message-submit').click();
            }
        };

        document.querySelector('#chat-message-submit').onclick = function(e) {
            var messageInputDom = document.getElementById('chat-message-input');
            var message = messageInputDom.value;
            if (!message) return

            // self-defined protocol to communicate with the server
            // the object being serialized must have `action` to be consumed by the server, otherwise
            // the message will be discarded 

            // action must follow the normal API specifications 
            chatSocket.send(JSON.stringify({
                'action': 'create_message',
                'message': message,
                'opponent_username': opponent_username,
                // 'from': username
            }));

            messageInputDom.value = '';
        };

        // function fetchMessages() {
        //     chatSocket.send(JSON.stringify({
        //         'command': 'fetch_messages'
        //     }));
        // }

        function createMessage(data, insertMethod = 'append') {

            var author = data.author;
            var msgListTag = document.createElement('li');
            var imgTag = document.createElement('img');
            var pTag = document.createElement('p');
            pTag.textContent = data.message;
            imgTag.src = 'http://emilcarlsson.se/assets/mikeross.png';

            if (author === username) {
                msgListTag.className = 'sent';
            } else {
                msgListTag.className = 'replies';
            }

            msgListTag.appendChild(imgTag);
            msgListTag.appendChild(pTag);
            // console.log(msgListTag)
            if (insertMethod == 'append'){
                document.querySelector('#chat-log').appendChild(msgListTag);
            }else if (insertMethod == 'prepend'){
                document.querySelector('#chat-log').prepend(msgListTag);
            }
            // scroll message section
            // $(".messages").animate({ scrollTop: $(document).height() }, "fast");
        }

        // init messages
        function init_message() {
            var page = Number($('#loadmore').data('page'))
            $.getJSON("{% url 'chatter_api:message' %}",{dialog_id:roomPk, page:page},
                function (data, textStatus, jqXHR) {
                    var results = data.results;
                    $('#loadmore').data('page', page+1)
                    console.log(results);
                    $.each(results, function (i, element) { 
                        createMessage(element, 'prepend')
                    });

                    if (data.next == null) $('#loadmore').removeClass('d-flex').addClass('d-none').prop('disable', false)
                }
            );
        }
        init_message()
        $('#loadmore').on('click', function(){
            init_message()
        })
    </script>
</body>

</html>