{% extends "base.html" %}

{% block title %}OpenWRT ACP{% endblock %}

{% block page_content %}

    <style type="text/css">
        {% include "css/bootstrap-editable.css" %}

        .table > tbody > tr > td {
            vertical-align: middle;
        }

        .table > tbody > tr > th {
            vertical-align: middle;
        }
    </style>

    <div class="page-header">
        <h3><strong>Access Points ({{ openwrt_subnet }})</strong></h3>
    </div>

    <table id="openwrts_table" class="table table-striped table-hover table-bordered">
        <thead class="head">
        <tr>
            <th scope="col">Name</th>
            <th scope="col">IP Address</th>
            <th scope="col">Ping</th>
            <th scope="col">LuCI</th>
            <th scope="col">SSH</th>
            <th scope="col">Hostname</th>
            <th scope="col">Firmware</th>
            <th scope="col">Uptime</th>
            <th scope="col">Clients</th>
            <th scope="col" data->Comment</th>
            <th scope="col">WiFi channel</th>
            <th scope="col">Actions</th>
        </tr>
        </thead>
        <tbody>
        {% for openwrt in openwrts %}
            {% set openwrt_url = 'http://' + openwrt.ip_address %}
            {% set comment = openwrt.comment %}
            {% if comment == '' %}{% set comment = '-' %}{% endif %}
            {% set openwrt_detail = url_for('main.openwrts', openwrt_name=openwrt.name) %}

            <tr name="{{ openwrt.name }}">
                <th scope="row" id={{ openwrt.name }} name="name">
                    <a name="openwrt_detail"
                       {% if openwrt.luci == False %}disabled{% else %}href="{{ openwrt_detail }}"{% endif %}
                       {% if openwrt.luci == False %}class="btn btn-sm btn-primary"
                       {% else %}class="btn btn-sm btn-primary"{% endif %}>{{ openwrt.name }}</a>
                </th>
                <td name="ip_address"><a href="{{ openwrt_url }}" target='_blank'>{{ openwrt.ip_address }}</a></td>
                <td name="ping" class="text-center">{{ render_tick_cross(openwrt.ping) }}</td>
                <td name="luci" class="text-center">{{ render_tick_cross(openwrt.luci) }}</td>
                <td name="ssh" class="text-center">{{ render_tick_cross(openwrt.ssh) }}</td>
                <td name="hostname" class="col-md-1">{{ openwrt.hostname }}</td>
                <td name="firmware" class="col-md-3">{{ openwrt.firmware }}</td>
                <td name="uptime" class="col-md-1">{{ openwrt.uptime }}</td>
                <td name="clients" class="col-md-1">{{ openwrt.clients }}</td>
                <td name="comment" class="col-md-2" style="word-wrap: break-word;min-width: 160px;max-width: 160px;">
                    <span href="#" name="comment" data-type="text" data-placement="top"
                          data-title="Enter comment" data-value="" style="cursor: pointer">
                        <div style="height:100%;width:100%;"><strong>{{ comment }}</strong></div>
                    </span>
                </td>
                <td name="channel" class="col-md-2">
                    <select class="form-control" id="channel_dropdown" name="channel_dropdown"
                            {% if openwrt.luci == False %}disabled{% endif %} required="">
                        <option value="auto" {% if openwrt.channel == 'auto' %}selected{% endif %}>auto</option>
                        <option value="1" {% if openwrt.channel == '1' %}selected{% endif %}>1 (2412 MHz)</option>
                        <option value="2" {% if openwrt.channel == '2' %}selected{% endif %}>2 (2417 MHz)</option>
                        <option value="3" {% if openwrt.channel == '3' %}selected{% endif %}>3 (2422 MHz)</option>
                        <option value="4" {% if openwrt.channel == '4' %}selected{% endif %}>4 (2427 MHz)</option>
                        <option value="5" {% if openwrt.channel == '5' %}selected{% endif %}>5 (2432 MHz)</option>
                        <option value="6" {% if openwrt.channel == '6' %}selected{% endif %}>6 (2437 MHz)</option>
                        <option value="7" {% if openwrt.channel == '7' %}selected{% endif %}>7 (2442 MHz)</option>
                        <option value="8" {% if openwrt.channel == '8' %}selected{% endif %}>8 (2447 MHz)</option>
                        <option value="9" {% if openwrt.channel == '9' %}selected{% endif %}>9 (2452 MHz)</option>
                        <option value="10" {% if openwrt.channel == '10' %}selected{% endif %}>10 (2457 MHz)</option>
                        <option value="11" {% if openwrt.channel == '11' %}selected{% endif %}>11 (2462 MHz)</option>
                    </select>
                </td>
                <td name="actions" class="col-md-2">
                    <button name="update_btn" wrt="{{ openwrt.name }}" class="btn btn-sm btn-primary"
                            href="/openwrts/update/{{ openwrt.name }}"
                            {% if openwrt.luci == False %}disabled{% endif %}>
                        <i class="glyphicon glyphicon-upload"></i> Update
                    </button>
                </td>
            </tr>
        {% endfor %}
        </tbody>
    </table>

    <div class="page-header"/>
    <div>
        <button id="refresh" class="btn btn-primary btn-lg" type="button">Scan Network</button>
        <span id="refresh_status" style="display:none">
            <img style="padding-left: 10px" src="/static/img/loading_32.gif" alt="Loading"
                 style="vertical-align:middle"/>
            <span style="padding-left: 5px">Refreshing statuses of all OpenWRTs ...</span>
        </span>
    </div>

    <div id="refresh_section" style="display:block; max-width: 100%">
        <span id="refresh_text" style="padding-top: 10px; display:inline-block; font-weight: bold">
            OpenWRT refresh status
        </span>
        <div class="progress" style="width: 50%; margin-top: 10px">
            <div id="progress_bar" class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0"
                 aria-valuemin="0"
                 aria-valuemax="100" style="width: 0%">
                <span class="progress-bar-label">0/0</span>
            </div>
        </div>
    </div>

{% endblock %}

{% block scripts %}
    {{ super() }}

    <script src="{{ url_for('static', filename='js/bootstrap-editable.min.js') }}"></script>

    <script>
        var refresh_status = function (json_data) {
            var progress = (json_data.updated_openwrts / json_data.total_openwrts) * parseFloat(100)

            $('.progress-bar').css('width', progress + '%').attr('aria-valuenow', progress);
            $('.progress-bar-label').text(json_data.updated_openwrts + '/' + json_data.total_openwrts);

            if (json_data.total_openwrts == null || json_data.total_openwrts == 0) {
                $('#refresh_text').html('Scan status is unknown');
                $('#progress_bar').removeClass('active');
            }
            else if (json_data.updated_openwrts == json_data.total_openwrts) {
                $('#refresh_text').html('Scan finished &#10004; (' + json_data.timestamp + ')');
                // ?
                //$('#progress_bar').removeClass('active');
            }
            else {
                $('#refresh_text').html('Scan in progress (' + json_data.current_openwrt + ') ...');
                $('#progress_bar').addClass('active');
            }
        };

        $(document).ready(function () {
            $.fn.editable.defaults.mode = 'inline';
            $('span[name=comment]').editable();
            $('span[name=comment]').on('save', function (e, params) {
                var openwrtName = $(this).closest('tr').find('th').first().attr('id');
                console.log('OpenWRT name: ' + openwrtName);

                $.ajax({
                    type: 'POST',
                    url: '/openwrt/comment',
                    data: JSON.stringify({
                        openwrt_name: openwrtName,
                        comment: params.newValue
                    }),
                    contentType: "application/json",
                    dataType: 'json'
                });
            });

            $('a[name=openwrt_detail]').click(function () {
                var openwrtName = $(this).closest('tr').find('th').first().attr('id');
                console.log('OpenWRT name: ' + openwrtName);
            });
        });

        namespace = '/ws';
        var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);

        socket.on('connect', function () {
            console.log('connected');
        });
        socket.on('refresh_status', function (data) {
            refresh_status(data);
        });
        socket.on('update_status', function (data) {
            if (data.status_type == "started") {
                toastr.info('Configuration update started.', data.openwrt_name);
            }
            else if (data.status_type == "error") {
                toastr.error(data.reason, data.openwrt_name);
            }
            else if (data.status_type == "finished") {
                toastr.success('Configuration update finished.', data.openwrt_name);
            }
            else {
                toastr.error('Unknown update status msg');
            }
        });
        socket.on('openwrts_updated', function (data) {
            location.reload();
            /*$('#openwrts_table').replaceWith((data.table));
            jQuery.ready();*/
        });

        $('select[name=channel_dropdown]').on('change', function () {
            var openwrtName = $(this).closest('tr').find('th').first().attr('id');
            var channel = this.value;
            console.log(channel + ": " + openwrtName);

            socket.emit('update_channel', {"openwrt_name": openwrtName, channel: channel})
        });

        $('button[name=update_btn]').on('click', function () {
            //console.log("clicked: ", $(this).getAttribute('href'));
            var update_endpoint = $(this)[0].getAttribute('href');
            var name = $(this)[0].getAttribute('wrt');
            console.log(name);

            socket.emit('update_openwrt', {"openwrt_name": name})
        });

        $('#refresh').click(function () {
            var refresh_section = $('#refresh_section');
            refresh_section.show();

            $.ajax({
                type: 'POST',
                url: '/openwrt/refresh_all',
                success: function (data, textStatus, xhr) {
                    $('#refresh_text').text('Started status refresh job of OpenWRTs ...');
                },
                error: function (data) {
                    if (data.status == 409) {
                        $('#refresh_text').text('Refresh already in progress ...');
                    }
                    else {
                        $('#refresh_text').text('Server error.');
                    }
                },
                complete: function (data) {
                },
            });
        });
    </script>
{% endblock %}