{% 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' %}" />
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href='{% static "css/emoji.css" %}'>

</head>

<body>

    <div id="frame">
        <!-- <input type="text" placeholder='wtfsssssssssssssssss' data-emojiable="true" data-emoji-input="unicode" /> -->
        <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.users}}">
                        <li class="contact {% if dialog_user.users == 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.users}}</p>
                                    <p class="preview">{{dialog_user.last_message}}</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..." data-emojiable="true" data-emoji-input="unicode" />
                    <div class="image-upload">
                        <label for="file-input">
                            <i class="fa fa-paperclip attachment" aria-hidden="true"></i>
                        </label>
                        <input id="file-input" type="file" />
                    </div>
                    <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')
        }

        function containsFile(data) {
            if (data.containsFile) return true
        }

        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)
            // console.log(data.message)

            // detect contains file
            if (data.message.startsWith('data:image')) {
                console.log(data);
                createMessage(data, insertMethod = 'append', image = true, src = data.message)
            } else {
                createMessage(data)
            }

            $(".messages").animate({
                scrollTop: $('.messages')[0].scrollHeight
            }, "fast");
            // 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 = '';
            $('.emoji-wysiwyg-editor').text('')
            $('.emoji-wysiwyg-editor').focus()
        };

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

        function createMessage(data, insertMethod = 'append', image = false, src = '', imageOption = {
            height: 150,
            width: 150
        }) {

            var author = data.author;
            var msgListTag = document.createElement('li');

            // avatarimage => name conflicts TODO: refactor
            var imgTag = document.createElement('img');
            imgTag.src = 'http://emilcarlsson.se/assets/mikeross.png';
            msgListTag.appendChild(imgTag);

            if (image == true) {
                //  TODO styling
                var imageTag = document.createElement('img');
                imageTag.src = src
                imageTag.style.cssText = `border-radius:0px;height:${imageOption.height}px;width:${imageOption.width}px`

                // imageTag.style.height = `${imageOption.height}px` | 200
                // imageTag.style.width = `${imageOption.width}px` | 200
                // imageTag.style.bordeRadius = '0px'
                msgListTag.appendChild(imageTag);
                console.log(imageTag)
                    // change height, width
            } else {
                var pTag = document.createElement('p');
                pTag.textContent = data.message;
                msgListTag.appendChild(pTag);
            }

            if (author === username) {
                msgListTag.className = 'sent';
            } else {
                msgListTag.className = 'replies';
            }
            // 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");
        }

        function _isB64encoded(value) {
            return value.includes(';base64,') ? true : false
        }

        // init messages
        function init_message(get_down = false) {
            get_down = get_down
            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)
                    $.each(results, function(i, element) {
                        // check if element.message is b64 encoded, extremly ugly
                        if (_isB64encoded(element.message)) {
                            createMessage(element, 'prepend', image = true, src = element.message)
                        } else {
                            createMessage(element, 'prepend')
                        }
                    });
                    console.log(data.next == null);
                    if (data.next == null) $('#loadmore').css({
                        'display': 'none'
                    }).prop('disable', false)
                    if (get_down) $(".messages").animate({
                        scrollTop: $('.messages')[0].scrollHeight
                    }, 0);

                }
            );
        }
        init_message(true)

        $('#loadmore').on('click', function() {
            init_message(false)
        })
    </script>

    <script>
        var max_height = 600;
        var max_width = 800;

        function resizeMe(img) {
            var canvas = document.createElement('canvas');
            var width = img.width;
            var height = img.height;
            // calculate the width and height, constraining the proportions
            if (width > height) {
                if (width > max_width) {
                    //height *= max_width / width;
                    height = Math.round(height *= max_width / width);
                    width = max_width;
                }
            } else {
                if (height > max_height) {
                    //width *= max_height / height;
                    width = Math.round(width *= max_height / height);
                    height = max_height;
                }
            }

            // resize the canvas and draw the image data into it
            canvas.width = width;
            canvas.height = height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, width, height);

            // preview.appendChild(canvas); // do the actual resized preview

            return canvas.toDataURL("image/jpeg", 0.7); // get the data from canvas as 70% JPG (can be also PNG, etc.)

        }

        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                // compress the image
                reader.onload = function(e) {
                        // get blob url
                        let buffer = e.target.result
                            // alert('haha')
                        var blob = new Blob([event.target.result]);
                        // console.log(typeof buffer)

                        var blobURL = window.URL.createObjectURL(blob);
                        // new image
                        var image = new Image();
                        image.src = blobURL;
                        var fileBase64;

                        // image onload
                        image.onload = function() {
                            // have to wait till it's loaded
                            var resized = resizeMe(image); // send it to canvas
                            fileBase64 = resized;
                            // console.log(fileBase64);
                            chatSocket.send(JSON.stringify({
                                'action': 'create_message',
                                'message': fileBase64,
                                'opponent_username': opponent_username,
                                // 'from': username
                            }));
                        }
                    }
                    // encode b64
                    // reader.readAsDataURL(input.files[0]);
                buffer = reader.readAsArrayBuffer(input.files[0]);
            }
        }

        const fileSelector = document.getElementById('file-input');
        fileSelector.addEventListener('change', (event) => {
            readURL(fileSelector);
        });

    </script>


    <script src="{% static 'js/config.js' %}"></script>
    <script src="{% static 'js/util.js' %} "></script>
    <script src="{% static 'js/jquery.emojiarea.js' %}"></script>
    <script src="{% static 'js/emoji-picker.js' %}"></script>

    <script>
        // Initializes and creates emoji set from sprite sheet
        window.emojiPicker = new EmojiPicker({
            emojiable_selector: '[data-emojiable=true]',
            assetsPath: '../static/img',
            popupButtonClasses: 'fa fa-smile-o'
        });
        // Finds all elements with emojiable_selector and converts them to rich emoji input fields
        // You may want to delay this step if you have dynamically created input fields that appear later in the loading process
        // It can be called as many times as necessary; previously converted input fields will not be converted again
        window.emojiPicker.discover();
    </script>

</body>

</html>