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

{% block title %}Scanner: {{ scanner_id }}{% endblock %}

{% block content %}
<div class="row mb-3">
    <div class="col-8">
        <div class="input-group">
            <input class="form-control" type="text" maxlength="40" id="container_id" placeholder="Container ID">
            <input class="form-control" type="text" maxlength="40" id="asset_id" placeholder="Asset ID">
        </div>
    </div>
    <div class="col-2">
        <div class="input-group">
            <input class="btn btn-primary" id="book-in-button" type="button" value="+Book">
            <input class="btn btn-primary" id="book-out-button" type="button" value="-Book">
        </div>
    </div>
    <div class="col-8">
        <div class="input-group">
            <textarea class="form-control" readonly="readonly" rows="4" id="container_details"></textarea>
            <textarea class="form-control" readonly="readonly" rows="4" id="asset_details"></textarea>
        </div>
    </div>
</div>
<div class="row">
    <div class="input-group">
        <textarea class="form-control mb-2" id="chat-log" cols="100" rows="10"></textarea>
        <input class="btn btn-secondary" id="clear-chat-area" type="button" value="Clear">
    </div>
    <div class="input-group">
        <input class="form-control" id="chat-message-input" type="text" size="100">
        <input class="btn btn-primary" id="chat-message-submit" type="button" value="Send">
    </div>
</div>
    {{ scanner_id|json_script:"scanner_id" }}
    <script>
        const scannerId = JSON.parse(document.getElementById('scanner_id').textContent);
        var containerIsValid = false;
        var assetIsValid = false;

        const chatSocket = new WebSocket(
            'ws://'
            + window.location.host
            + '/ws/scanner/'
            + scannerId
            + '/'
        );

        async function getContainerInfo(containerId) {
            document.querySelector('#container_id').value = containerId;
            url = '/api/containers?named_id=' + containerId;
            document.querySelector('#container_details').value = 'Trying ' + url;
            const response = await fetch(url);
            const container = await response.json();
            if (container.count >= 1) {
                document.querySelector('#container_details').value = container.results[0].description;
                containerIsValid = true;
            } else {
                document.querySelector('#container_details').value = document.querySelector('#container_details').value + "\nERROR: No result\n";
                console.log(response);
                containerIsValid = false;
            }
        }

        async function getAssetInfo(assetId) {
            document.querySelector('#asset_id').value = assetId;
            url = '/api/assets?named_id=' + assetId;
            document.querySelector('#asset_details').value = 'Trying ' + url;
            const response = await fetch(url);
            const asset = await response.json();
            if (asset.count >= 1) {
                document.querySelector('#asset_details').value = asset.results[0].description;
                assetIsValid = true;
            } else {
                document.querySelector('#asset_details').value = document.querySelector('#asset_details').value + "\nERROR: No result\n";
                console.log(response);
                assetIsValid = false;
            }
        }

        chatSocket.onmessage = function(e) {
            const data = JSON.parse(e.data);
            msg = String(data.message);
            document.querySelector('#chat-log').value += (msg + '\n');
            if (msg.startsWith('C-')) {
                getContainerInfo(data.message);
                // document.querySelector('#container_id').value = msg;
            } else if (msg.startsWith('A-')) {
                getAssetInfo(data.message);
                // document.querySelector('#asset_id').value = msg;
            } else {
                assetId = 'A-' + msg;
                document.querySelector('#asset_id').value = assetId;
                getAssetInfo(assetId);
            }
        };

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

        document.querySelector('#chat-message-input').focus();
        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) {
            const messageInputDom = document.querySelector('#chat-message-input');
            const message = messageInputDom.value;
            chatSocket.send(JSON.stringify({
                'message': message
            }));
            messageInputDom.value = '';
        };

        document.querySelector('#clear-chat-area').onclick = function(e) {
            document.querySelector('#chat-log').value = "cleared\n";
        }

        document.querySelector('#book-in-button').onclick = function(e) {
            if (!containerIsValid) {
                msg = 'Cannot book-in as container is invalid';
                console.log(msg);
                document.querySelector('#chat-log').value += ('ERROR: ' + msg + '\n');
                return;
            }
            if (!assetIsValid) {
                msg = 'Cannot book-in as asset is invalid';
                console.log(msg);
                document.querySelector('#chat-log').value += ('ERROR: ' + msg + '\n');
                return;
            }
        }

        document.querySelector('#book-out-button').onclick = function(e) {
            if (!containerIsValid) {
                msg = 'Cannot book-out as container is invalid';
                console.log(msg);
                document.querySelector('#chat-log').value += ('ERROR: ' + msg + '\n');
                return;
            }
            if (!assetIsValid) {
                msg = 'Cannot book-out as asset is invalid';
                console.log(msg);
                document.querySelector('#chat-log').value += ('ERROR: ' + msg + '\n');
                return;
            }
        }

    </script>
{% endblock %}
