{% extends 'base.html.twig' %}
{% block title %}Zařízení | Detail{% endblock %}
{% block body %}
<!-- Content Header (Page header) -->
<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1>Zařízení: {{ device.name }}</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="{{ path('device_activate', {'id':device.id, 'origin':app.request.attributes.get('_route')}) }}">Zařízení</a></li>
                    <li class="breadcrumb-item active">Detail zařízení: {{ device.name }}</li>
                </ol>
            </div>
        </div>
        {% if is_granted('ROLE_ADMIN') %}
            <div class="row">
                <div class="col-md-1 pt-1 text-right ml-auto">
                    <a href="{{ path('devices_settings',{'id':device.id,'origin':app.request.attributes.get('_route')}) }}" class="btn btn-primary w-100" title="Nastavení">
                        <i class="fa-fw fas fa-cog"></i>
                    </a>
                </div>
                <div class="col-md-1 pt-1 text-right">
                    <a href="{{ path('devices_update',{'id':device.id,'origin':app.request.attributes.get('_route')}) }}" title="Editovat zařízení" class="btn btn-primary w-100">
                        <i class="fa-fw fas fa-pen"></i>
                    </a>
                </div>
            </div>
        {% endif %}
    </div><!-- /.container-fluid -->
</section>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        {% for message in app.flashes('good') %}
            <div class="flash-notice pull-right col-xs-12 " style="padding:0;">
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <strong>{{ message|raw }}</strong>
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
        {% endfor %}
        {% for message in app.flashes('bad') %}
            <div class="flash-notice pull-right col-xs-12 " style="padding:0;">
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <strong>{{ message|raw }}</strong>
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
        {% endfor %}
        <div class="row connectedSortable ui-sort">
            <div class="col-lg-6 d-flex">
                <div class="card card-primary card-outline  w-100">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-fw fa-desktop"></i>
                            Detail
                        </h3>
                    </div>
                    <!-- /.card-header -->
                    <div class="card-body">
                        <dl>
                            <dt>MAC adresa:</dt>
                            <dd>{{ device.macAddress }}</dd>
                            {% if device.localIpAddress is defined and device.localIpAddress is not empty %}
                            <dt>Lokální IP adresa:</dt>
                            <dd>{{ device.localIpAddress }}</dd>
                            {% endif %}
                            <dt>Poznámka:</dt>
                            <dd>{{ device.note }}</dd>
                            {% if is_granted('ROLE_ADMIN') %}
                                <dt>Unikátní klíč:</dt>
                                <dd>{{ device.uniqueHash }}</dd>
                            {% endif %}
                            <dt>Interval zápisu:</dt>
                            <dd>
                                {% if writeInterval is defined and writeInterval is not empty %}
                                    {{ writeInterval.description }}
                                {% endif %}
                            </dd>
                            <dt>Stav notifikací:</dt>
                            <dd>
                                {% if deviceOptions.notificationsStatus == 1 %}
                                    Zapnuto
                                {% else %}
                                    Vypnuto
                                {% endif %}
                            </dd>
                            {% if deviceOptions.notificationsStatus == 1 %}
                                <dt>Odesílat notifikace uživateli:</dt>
                                <dd>
                                    {{ deviceOptions.notificationsTargetUser.username }}
                                </dd>
                            {% endif %}
                        </dl>
                    </div>
                    <!-- /.card-body -->
                </div>
                <!-- /.card -->
            </div>
            {% if sensors is defined and sensors is not empty %}
                {% for sensor in sensors %}
                    <div class="col-lg-6">
                        <!-- interactive chart -->
                        {% set state = 'card-warning' %}
                        {% if sensorsState is defined and sensorsState is not empty %}
                            {% for sensorState in sensorsState %}
                                {% if sensorState.id == sensor.id %}
                                    {% if sensorState.state == true %}
                                        {% set state = 'card-green' %}
                                    {% else %}
                                        {% set state = 'card-danger' %}
                                    {% endif %}
                                {% endif %}
                            {% endfor %}
                        {% endif %}
                        <div class="card card-outline {{ state }}">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="far fa-fw fa-chart-bar"></i>
                                    Senzor: {{ sensor.hardwareId }} {% if state == 'card-danger' %}(<span class="font-weight-bold text-danger">Neaktivní</span>){% endif %}
                                </h3>
                                {% if is_granted('ROLE_ADMIN') %}
                                <div class="card-tools">
                                   <a href="{{ path('sensor_remove',{'id':sensor.Id, 'origin': origin}) }}" class="text-danger" title="Odebrat senzor">
                                       <i class="fa-fw fas fa-trash"></i>
                                   </a>
                                </div>
                                {% endif %}
                            </div>
                            <div class="card-body">
                                <div id="{{ sensor.hardwareId }}" style="height: 300px;"></div>
                            </div>
                            <!-- /.card-body-->
                        </div>
                        <!-- /.card -->
                    </div>
                    <!-- /.col -->
                {% endfor %}
            {% endif %}
        </div>
        <!-- /.row -->
    </div><!-- /.container-fluid -->
</section>
<!-- /.content -->
{% endblock %}
{% block stylesheets %}
    {{ parent() }}
    <!-- DataTables -->
    <link rel="stylesheet" href="{{ asset('plugins/datatables-bs4/css/dataTables.bootstrap4.min.css') }}">
    <link rel="stylesheet" href="{{ asset('plugins/datatables-responsive/css/responsive.bootstrap4.min.css') }}">
    <link rel="stylesheet" href="{{ asset('plugins/datatables-buttons/css/buttons.bootstrap4.min.css') }}">
{% endblock %}
{% block javascripts %}
    {{ parent() }}
    <!-- DataTables  & Plugins -->
    <script src="{{ asset('plugins/datatables/jquery.dataTables.min.js') }}"></script>
    <script src="{{ asset('plugins/datatables-bs4/js/dataTables.bootstrap4.min.js') }}"></script>
    <script src="{{ asset('plugins/datatables-responsive/js/dataTables.responsive.min.js') }}"></script>
    <script src="{{ asset('plugins/datatables-responsive/js/responsive.bootstrap4.min.js') }}"></script>
    <script src="{{ asset('plugins/datatables-buttons/js/dataTables.buttons.min.js') }}"></script>
    <script src="{{ asset('plugins/datatables-buttons/js/buttons.bootstrap4.min.js') }}"></script>
    <script src="{{ asset('plugins/jszip/jszip.min.js') }}"></script>
    <script src="{{ asset('plugins/pdfmake/pdfmake.min.js') }}"></script>
    <script src="{{ asset('plugins/pdfmake/vfs_fonts.js') }}"></script>
    <script src="{{ asset('plugins/datatables-buttons/js/buttons.html5.min.js') }}"></script>
    <script src="{{ asset('plugins/datatables-buttons/js/buttons.print.min.js') }}"></script>
    <script src="{{ asset('plugins/datatables-buttons/js/buttons.colVis.min.js') }}"></script>
    <!-- FLOT CHARTS -->
    <script src="{{ asset('plugins/flot/jquery.flot.js') }}"></script>
    <!-- FLOT RESIZE PLUGIN - allows the chart to redraw when the window is resized -->
    <script src="{{ asset('plugins/flot/plugins/jquery.flot.resize.js') }}"></script>
    <!-- FLOT PIE PLUGIN - also used to draw donut charts -->
    <script src="{{ asset('plugins/flot/plugins/jquery.flot.pie.js') }}"></script>
    <!-- Page specific script -->
    <script>
        $(function () {
            var totalPoints = 90;
            var pushvalue = 0;
            var sensorData = []

            //loads sensorids for graphs generation
            const chartIds = {{ sensorIds|striptags|raw|nl2br }};
            chartIds.forEach(device=>{
                sensorData[device] = []
                var interactive_plot = $.plot('#'+device+'', [
                        {
                            data: getData(device),
                        }
                    ],
                    {
                        grid: {
                            borderColor: '#f3f3f3',
                            borderWidth: 1,
                            tickColor: '#f3f3f3',
                            clickable: true,
                            hoverable: true,
                            mouseActiveRadius: 15,
                        },
                        series: {
                            shadowSize: 0, // Drawing is faster without shadows
                            color: '#3c8dbc',
                            lines: {
                                lineWidth: 2,
                                show: true,
                                fill: true,
                            },
                            points: {
                                show: true
                            },
                        },
                        yaxis: {
                            show: true,
                            options: {
                                autoScale: "exact"
                            }

                        },
                        xaxis: {
                            show: true
                        }
                    }
                )
                //sets update interval from steps
                var updateInterval = {{ writeInterval.secondsSteps*1000 }} //Fetch data ever x milliseconds
                var realtime       = 'on' //If == to on then fetch data every x seconds. else stop fetching
                function update() {
                    if (pushvalue !== 0)
                    {
                        interactive_plot.setData([getData(device)])
                    }
                    interactive_plot.setupGrid(true)
                    interactive_plot.draw()

                    if (chartIds.at(-1) === device)
                    {
                        pushvalue = pushvalue + 1;
                    }
                    if (realtime === 'on') {
                        setTimeout(update, updateInterval)
                    }
                }

                //INITIALIZE REALTIME DATA FETCHING
                if (realtime === 'on') {
                    update()
                }
                $("#"+device+"").bind("plothover", function (event, pos, item) {
                    if (item) {
                        if (previousPoint !== item.dataIndex) {

                            previousPoint = item.dataIndex;

                            $("#tooltip").remove();
                            var x = item.datapoint[0].toFixed(2),
                                y = item.datapoint[1].toFixed(2);

                            showTooltip(item.pageX, item.pageY,
                                y+" °C");
                        }
                    } else {
                        $("#tooltip").remove();
                        previousPoint = null;
                    }
                });
            })

            //fetches data by sensor
            function getData(sensorId) {
                var sensorDataLength = 0;
                //generates api url
                var getDataUrl = "{{ path('sensor_getData',{'id':device.id, 'hardwareId': '_hardwareId_'}) }}/"+pushvalue;
                getDataUrl = getDataUrl.replace("_hardwareId_", sensorId);
                $.ajax({
                    method: "GET",
                    url: getDataUrl,
                    dataType: "json",
                    async: false,

                    success: function(data) {
                        temperatures = data.temperatures;
                    }
                });
                sensorDataLength = sensorData[sensorId].length - 1
                var res = [];
                if(pushvalue === 0){
                    var pi = 0;

                    while (sensorData[sensorId].length < totalPoints) {
                        var prev = sensorData[sensorId].length > 0 ? sensorData[sensorDataLength] : 50,
                            y = temperatures[pi];
                        pi = pi+1;

                        sensorData[sensorId].push(y);
                    }
                    // Zip the generated y values with the x values


                    for (var i = 0; i < sensorData[sensorId].length; ++i) {

                        if (sensorData[sensorId][i]){
                            res.push([i, sensorData[sensorId][i]])
                        }else {
                            res.push([i, 0])
                        }

                    }
                    return res;
                }else{
                    if (sensorData[sensorId].length > 0)
                        sensorData[sensorId] = sensorData[sensorId].slice(1);

                    sensorDataLength = sensorData[sensorId].length - 1

                    while (sensorData[sensorId].length < totalPoints) {
                        var prev = sensorData[sensorId].length > 0 ? sensorData[sensorId][sensorDataLength] : 50, y = temperatures;
                        sensorData[sensorId].push(y);
                    }
                    // Zip the generated y values with the x values
                    for (var i = 0; i < sensorData[sensorId].length; ++i) {

                        if (sensorData[sensorId][i]){
                            res.push([i, sensorData[sensorId][i]])
                        }else {
                            res.push([i, 0])
                        }

                    }
                    return res;
                }

            }
        })

        function showTooltip(x, y, contents) {
            $("<div id='tooltip'>" + contents + "</div>").css({
                position: "absolute",
                display: "none",
                top: y + 5,
                left: x - 40,
                border: "1px solid #fdd",
                padding: "2px",
                "background-color": "#fee",
                opacity: 0.80
            }).appendTo("body").fadeIn(200);
        }

    </script>
{% endblock %}
