{% extends app['twig_theme'] ~ '/' ~ 'layout.twig' %}

{% set title = 'Mainpage'|trans ~ ': ' ~ 'Dashboard'|trans %}


{% block footer_js %}
        {{ parent() }}
        {% include app.twig_theme ~ "/basic_templates/scripts-datatables.twig" %}

        <script src='//www.google.com/jsapi?autoload={"modules":[{"name":"visualization","version":"1","packages":["corechart"],"callback":"load_page_data"}]}'></script>

        <script src="{{app.request_context.baseUrl}}/plugins/flot/jquery.flot.js"></script>
        <script src="{{app.request_context.baseUrl}}/plugins/flot/jquery.flot.time.js"></script>
        <script src="{{app.request_context.baseUrl}}/plugins/flot/jquery.flot.navigate.js"></script>

{% endblock %}


{% block content %}
    <div id="iptv_list" class="dashboard">
        <div class="row  filters-actions-pannel">
           <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <button type="button" class="btn btn-success  pull-right" id="auto-update-button">{{ 'Auto-update within 59 seconds'|trans }}</button>
            </div>
        </div>
        <div class="row">
            <br>
            <div class="col-xs-12 col-sm-5">
                <div class="box">
                    <a class="collapse-link">
                        <div class="box-header">
                            <div class="box-name">
                                <span>{{ 'Statistisc'|trans }}</span>
                            </div>
                            <div class="circle-button box-icons">
                                <i class="fa fa-chevron-up"></i>
                            </div>
                            <div class="no-move"></div>
                        </div>
                    </a>
                    <div class="box-content">
                        <div class="dataTables_processing"></div>
                        <table class="table  table-hover table-datatable" id="datatable-1">
                            <thead>
                            <tr>
                                <th data-filter="category">{{ 'Category'|trans }}</th>
                                <th data-filter="number">{{ 'Number'|trans }}</th>
                            </tr>
                            </thead>
                            <tbody>
                            {% if attribute(app, 'datatables') is defined and attribute(app.datatables, 'datatable-1') is defined %}
                            {%  autoescape false %}
                                {% for item in app.datatables['datatable-1'].data %}
                                    <tr>
                                        <td>{{ item.category }}</td>
                                        <td>{{ item.number }}</td>
                                    </tr>
                                {% endfor %}
                            {% endautoescape %}
                            {% endif %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            {% if attribute(app, 'datatables') is defined and attribute(app.datatables, 'datatable-2') is defined and attribute(app.datatables['datatable-2'], 'data') is defined %}
            <div class="col-xs-12 col-sm-7">
                <div class="box">
                    <a class="collapse-link">
                        <div class="box-header">
                            <div class="box-name">
                                <span>{{ 'Storages (measured in the number of the current session)'|trans }}</span>
                            </div>
                            <div class="circle-button box-icons">
                                <i class="fa fa-chevron-up"></i>
                            </div>
                            <div class="no-move"></div>
                        </div>
                    </a>
                    <div class="box-content">
                        <div class="dataTables_processing"></div>
                        <table class="table  table-hover table-datatable" id="datatable-2">
                            <thead>
                            <tr>
                                <th data-filter="storage">{{ 'Storage name'|trans }}</th>
                                <th data-filter="video">{{ 'Video club'|trans }}</th>
                                <th data-filter="tv_archive">{{ 'Tv archive'|trans }}</th>
                                <th data-filter="timeshift">{{ 'Timeshift'|trans }}</th>
                                <th data-filter="loading">{{ 'Loading'|trans }}</th>
                            </tr>
                            </thead>
                            <tbody>
                                {%  autoescape false %}
                                {% for item in app.datatables['datatable-2'].data %}
                                    <tr>
                                        <td>{{ item.storage }}</td>
                                        <td>{{ item.video }}</td>
                                        <td>{{ item.tv_archive }}</td>
                                        <td>{{ item.timeshift }}</td>
                                        <td>{{ item.loading }}</td>
                                    </tr>
                                {% endfor %}
                                {% endautoescape %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            {% endif %}
            {% if attribute(app, 'datatables') is defined and attribute(app.datatables, 'datatable-3') is defined and attribute(app.datatables['datatable-3'], 'data') is defined %}
            <div class="col-xs-12 col-sm-5">
                <div class="box">  <a class="collapse-link">
                    <div class="box-header">
                        <div class="box-name">
                            <span>{{ 'Streaming servers'|trans }}</span>
                        </div>
                        <div class="circle-button box-icons">
                                <i class="fa fa-chevron-up"></i>
                        </div>
                        <div class="no-move"></div>
                    </div> </a>
                    <div class="box-content">
                        <div class="dataTables_processing"></div>
                        <table class="table  table-hover table-datatable" id="datatable-3">
                            <thead>
                            <tr>
                                <th data-filter="server">{{ 'Server name'|trans }}</th>
                                <th data-filter="sessions">{{ 'Number of sessions'|trans }}</th>
                                <th data-filter="loading">{{ 'Loading'|trans }}</th>
                            </tr>
                            </thead>
                            <tbody>
                                {%  autoescape false %}
                                {% for item in app.datatables['datatable-3'].data %}
                                    <tr>
                                        <td>{{ item.server }}</td>
                                        <td>{{ item.sessions }}</td>
                                        <td>{{ item.loading }}</td>
                                    </tr>
                                {% endfor %}
                                {% endautoescape %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            {% endif %}
        </div>
        <div class="row">
            <div class="col-xs-12 col-sm-8">
                <div class="box"><a class="collapse-link">
                    <div class="box-header">
                        <div class="box-name">
                            <span>{{ 'Users activity'|trans }}</span>
                        </div>
                        <div class="circle-button box-icons">
                                <i class="fa fa-chevron-up"></i>
                        </div>
                        <div class="no-move"></div>
                    </div> </a>
                    <div class="box-content" style="padding: 5px 0 5px 5px;">
                        <div id="visit-plot" style="min-height: 300px; left: 10px;"> </div>
                    </div>
                </div>
            </div>
            <div class="col-xs-6 col-sm-4">
                <div class="box">  <a class="collapse-link">
                    <div class="box-header">
                        <div class="box-name">
                            <span>{{ 'Popularity of services'|trans }}</span>
                        </div>
                        <div class="circle-button box-icons">
                                <i class="fa fa-chevron-up"></i>
                        </div>
                        <div class="no-move"></div>
                    </div> </a>
                    <div class="box-content">
                        <div id="google-chart-1" style="min-height: 300px;"> </div>
                        <br/>
                        <br/>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript" defer>
        var google = {};
        var updateTimerInterval = null;

        // Draw all test xCharts
        function DrawAllxCharts(data) {
            //  Chart 1
            var chart1_data = [
                ["Element", "", { role: "style" }, {type: 'string', role: 'tooltip', 'p': {'html': true}}],
                ['{{ 'Tv'|trans }}', data.tv.sessions, "#8FBE7B", '<span>{{ 'Total sessions'|trans }}: <b>'+data.tv.sessions+'</b></span> <br/> <span>{{ 'Popularity'|trans }}: <b>'+data.tv.percent+'%</b></span>'],
                ['{{ 'Radio'|trans }}', data.radio.sessions, "#F4D165", '<span>{{ 'Total sessions'|trans }}: <b>'+data.radio.sessions+'</b></span> <br/> <span>{{ 'Popularity'|trans }}: <b>'+data.radio.percent+'%</b></span>'],
                ['{{ 'Video'|trans }}', data.video.sessions, "#D94040", '<span>{{ 'Total sessions'|trans }}: <b>'+data.video.sessions+'</b></span> <br/> <span>{{ 'Popularity'|trans }}: <b>'+data.video.percent+'%</b></span>'],
                ['{{ 'Audio'|trans }}', data.audio.sessions, "#467EAF", '<span>{{ 'Total sessions'|trans }}: <b>'+data.audio.sessions+'</b></span> <br/> <span>{{ 'Popularity'|trans }}: <b>'+data.audio.percent+'%</b></span>'],
                ['{{ 'Karaoke'|trans }}', data.karaoke.sessions, "#C27BA0", '<span>{{ 'Total sessions'|trans }}: <b>'+data.karaoke.sessions+'</b></span> <br/> <span>{{ 'Popularity'|trans }}: <b>'+data.karaoke.percent+'%</b></span>']
            ];

            var chart1_options = {
                tooltip: {isHtml: true},
                backgroundColor: '#FFFFFF',
                chartArea: {width: '75%', height: '80%'},
                bar: {groupWidth: "95%"},
                vAxis: {
                    /*ticks: [0, data.all_sessions * , 20, 30, 40, 50],*/
                    viewWindow: {min: 0, max: data.all_sessions}
                },
                legend: { position: "none" }
            };
            if (typeof (google) == 'undefined') {
                google = window['google'];
            }
            var chart1_element = 'google-chart-1';
            var chart1_type = google.visualization.ColumnChart;
            drawGoogleChart(chart1_data, chart1_options, chart1_element, chart1_type);
        }

        function drawGoogleChart(chart_data, chart_options, element, chart_type) {
            if (typeof (google) == 'undefined') {
                google = window['google'];
            }
            // Function for visualize Google Chart
            var data = google.visualization.arrayToDataTable(chart_data);
            var chart = new chart_type(document.getElementById(element));
            chart.draw(data, chart_options);
        }

        function load_page_data(){
            if (typeof (window['google']) == 'undefined') {
                window['google'] = google;
            }
            $.ajax({
                dataType: 'json',
                type: 'post',
                url: '{{ app.request_context.baseUrl }}/index/index-datatable4-list-json',
                async: false,
                success: function(data){
                    if(data && data.data){
                        DrawAllxCharts(data.data);
                    }
                }
            });
        }

        function TestTable1() {
            $.extend( $.fn.dataTable.defaults, {
                "searching": false,
                "ordering": false,
                "processing": true,
                "serverSide": true,
                "bAutoWidth": false,
                "bFilter": false,
                "bPaginate": false,
                "bInfo": false,
                "bJQueryUI": true,
                'iDisplayLength': 5,
                'bLengthChange': false,
                "language": {
                    "url": "{{ app.datatable_lang_file }}"
                }
            } );

            {% if attribute(app, 'datatables') is defined %}
                {% for item in app.datatables %}
                    {% if attribute(item, 'data') is defined %}
            $('#{{ item.datatableID }}').on('xhr.dt', function (e, settings, json) {
                /*console.log(json);*/
            }).dataTable({
                "ajax": {
                    "url": "{{ app.request_context.baseUrl }}/index/{{ item.json_action_alias }}",
                    "data": function (d) {}
                },
                "deferLoading": {{ item.data|length }},
                {% if item.data|length %}
                "columns": [
                    {% for key,field in item.data.0 %}
                    {"data": "{{ key }}"}{% if not loop.last %}, {% endif %}
                    {% endfor %}
                ],
                {% endif %}
                "aoColumnDefs": [
                    /*{"width": '20%', "targets": [-3]}*/
                ]
            }).prev('.dataTables_processing').hide('');
            $('#{{ item.datatableID }}').DataTable().ajax.reload();
            /*$('#{{ item.datatableID }}').DataTable().order([0, 'desc']).draw();*/
                    {% endif %}
                {% endfor %}
            {% endif %}
        }

        function DrawFlot(){

            var d = [[0]];

            $.ajax({
                dataType: 'json',
                type: 'post',
                url: '{{ app.request_context.baseUrl }}/index/index-datatable5-list-json',
                async: false,
                success: function(data){
                    if(data && data.data && data.data.length){
                        d = data.data;
                    }
                }
            });

            // first correct the timestamps - they are recorded as the daily
            // midnights in UTC+0100, but Flot always displays dates in UTC
            // so we have to add one hour to hit the midnights in the plot
            var x = new Date();
            var utcOffset = (-x.getTimezoneOffset()) * 60 *1000;
            for (var i = 0; i < d.length; ++i) {
                d[i][0] = (d[i][0] * 1000 + utcOffset);
            }

            var options = {
                xaxis: {
                    mode: "time",
                    tickLength: 5,
                    position: 'bottom',
                    min: d[d.length > 48 ? d.length - 48 : 0][0],
                    dayNames : [
                        '{{ 'Sun'|trans }}',
                        '{{ 'Mon'|trans }}',
                        '{{ 'Tue'|trans }}',
                        '{{ 'Wed'|trans }}',
                        '{{ 'Thu'|trans }}',
                        '{{ 'Fri'|trans }}',
                        '{{ 'Sat'|trans }}'
                    ],
                    monthNames  : [
                        '{{ 'January'|trans }}',
                        '{{ 'February'|trans }}',
                        '{{ 'March'|trans }}',
                        '{{ 'April'|trans }}',
                        '{{ 'May'|trans }}',
                        '{{ 'June'|trans }}',
                        '{{ 'July'|trans }}',
                        '{{ 'August'|trans }}',
                        '{{ 'September'|trans }}',
                        '{{ 'October'|trans }}',
                        '{{ 'November'|trans }}',
                        '{{ 'December'|trans }}'
                    ]
                },
                yaxis: {
                    zoomRange: false,
                    panRange: false,
                    position: 'left'
                },
                grid: {
                    markings: weekendAreas,
                    borderColor: '#dddddd'
                },
                zoom: {
                    interactive: true
                },
                pan: {
                    interactive: true
                }
            };

            var plot = $.plot("#visit-plot", [d], options);

        }

        // helper for returning the weekends in a period

        function weekendAreas(axes) {

            var markings = [],
                    d = new Date(axes.xaxis.min);

            // go to the first Saturday

            d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 1) % 7))
            d.setUTCSeconds(0);
            d.setUTCMinutes(0);
            d.setUTCHours(0);

            var i = d.getTime();

            // when we don't set yaxis, the rectangle automatically
            // extends to infinity upwards and downwards

            do {
                markings.push({xaxis: {from: i, to: i + 2 * 24 * 60 * 60 * 1000}});
                i += 7 * 24 * 60 * 60 * 1000;
            } while (i < axes.xaxis.max);

            return markings;
        }

        function updateStatisticsButton(){
            $('#auto-update-button').text($('#auto-update-button').text().replace(/\d{1,2}/ig, '0'));
            updateTimer();
        }

        function updateStatistics(){
            var currText = $("#auto-update-button").text();
            $("#auto-update-button").text("{{ 'Processing'|trans }}...");
            var currTable = new $.fn.dataTable.Api( '.table-datatable' );
            currTable.ajax.reload();
            DrawFlot();
            load_page_data();
            $("#auto-update-button").text(currText);
        }

        function updateTimer(){
            if (updateTimerInterval) {
                clearInterval(updateTimerInterval);
            }
            updateTimerInterval = setInterval(function(){
                var regExp = /\d{1,2}/i;
                var curTime = regExp.exec($('#auto-update-button').text());
                if (isNaN(curTime)) {
                    curTime = 60;
                }
                if (curTime <= 1 || curTime >= 60) {
                    updateStatistics();
                    $('#auto-update-button').text($('#auto-update-button').text().replace(/\d{1,2}/ig, 59));
                    return;
                } else {
                    curTime = parseInt(curTime, 10);
                }
                $('#auto-update-button').text($('#auto-update-button').text().replace(/\d{1,2}/ig, curTime - 1));
            }, 1000)
        }

        function yelp() {
            $(document).ready(function () {

                $("#content, #main").css("background-color", "#f2f2f2");

                LoadDataTablesScripts(TestTable1);

                $(document).on('hide', '.dataTables_processing', function(e){
                    $(".dataTables_wrapper > div.row-fluid").hide();
                });
                $('#datatable-1 > thead').hide();

                DrawFlot();

                updateTimer();
                $(document).on('click', '#auto-update-button', function(){
                    updateStatisticsButton();
                });
            });
        }

        document.addEventListener("DOMContentLoaded", yelp, false);
    </script>
{% endblock %}
