{% extends "base.html" %}
{% load static %}

{% block title %}Scanner Index{% endblock %}

{% block content %}
<div class="container">
    <div class="row">
        <h1>Booker</h1>
        <p>Choose a scanner you want to use to book assets and container into/outof containers.</p>
    </div>
    <div class="row">
        <div class="cols-12">
        <textarea id="chat-log" cols="100" rows="7"></textarea><br>

        What scanner would you like to use? (Refresh page if your new scanner is not shown)<br>
        {% for scanner in object_list %}
        <a href="/booker/{{ scanner.named_id }}/">{{ scanner.named_id }}: {{ scanner.description }}</a><br />
        {% endfor %}
        <input id="scanner-name-input" type="text" size="100"><br>
        <input id="scanner-name-submit" type="button" value="Enter">

        <script>
            document.querySelector('#scanner-name-input').focus();
            document.querySelector('#scanner-name-input').onkeyup = function(e) {
                if (e.keyCode === 13) {  // enter, return
                    document.querySelector('#scanner-name-submit').click();
                }
            };

            document.querySelector('#scanner-name-submit').onclick = function(e) {
                var scannerName = document.querySelector('#scanner-name-input').value;
                window.location.pathname = '/booker/' + scannerName + '/';
            };
        </script>

        <script>
            const chatSocket = new WebSocket(
                'ws://'
                + window.location.host
                + '/ws/scanner-announce/'
            );

            chatSocket.onmessage = function(e) {
                const data = JSON.parse(e.data);
                document.querySelector('#chat-log').value += (data.scanner + ': ' + data.message + '\n');
            };

            chatSocket.onclose = function(e) {
                console.error('Chat socket closed unexpectedly');
                document.querySelector('#chat-log').value += ('ERROR: Chat socket closed unexpectedly!\n');
            };

        </script>
        </div>
    </div>
</div>
{% endblock %}
