{% extends "base.html" %}

{% block head %}
    {{ super() }}
    <script>
        var CSRF_TOKEN = "{{ csrf_token() }}";
    </script>
    <script src="{{ url_for('static', filename='js/min/common.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/min/rooms.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/min/devices.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/min/modals.min.js') }}"></script>
    <script>
        const scanNewDevices = function() {
            if (confirm("Scanning for new devices may take 10-20 seconds. Please be patient. This page will update shortly")) {
                let progress = m("div.d-flex.justify-content-center",
                    m("div.spinner-border", {role: "status"},
                        m("span.visually-hidden", "Scanning for new bluetooth devices...")
                    )
                );
                showModal(progress);
                setTimeout(function() { window.location.reload(); }, 10000);

                let route = API_URI + "/scan";
                return fetch(route, {
                    method: "GET",
                    credentials: 'same-origin',
                    headers: {
                        "X-CSRF-Token": CSRF_TOKEN,
                        "Content-Type": "application/json"
                    },
                }).then(function(response) {
                    if (response.ok) {
                        return response.json();
                    } else {
                        console.log("device scan request failed")
                    }
                }).then(function(data) {
                    // ok
                }).catch(function(err) {
                    console.log(err);
                })
            }
        }
    </script>
{% endblock %}

{% block content %}
<h3 class="mb-3">Devices</h3>
{%- if data -%}
    <div class="row row-cols-1 row-cols-lg-2">
    {%- for device in data -%}
        <div class="col">
            <a href="javascript:" onclick="deviceFormModal({{ device.id }})" class="btn btn-outline-primary my-1 w-100">{{ device.name }}
                {%- if not device.room_id -%}
                <span class="ml-2 badge rounded-pill bg-warning">new</span>
                {%- endif -%}
            </a>
        </div>
    {%- endfor -%}
    </div>
{%- endif -%}
{% if features %}
    {%- if features.attributes.device_limit > data | length -%}
    <div class="mt-3">
        <a href="javascript:" class="btn btn-outline-primary" onclick="scanNewDevices()">Discover New Devices</a>
    </div>
    {%- endif -%}
{% endif %}
{% endblock %}
