{% extends 'webapp/base.html' %}
{% load i18n %}
{% load crispy_forms_tags %}
{% load static %}
{% load compress %}
{% block style_block %}
    {% compress css %}
        <link rel="stylesheet" href="{% static "select2/select2.css" %}">
    {% endcompress %}
{% endblock %}
{% block sidebar_content %}
    <div class="panel">
        <div class="panel-heading">Filter source records</div>
        {% crispy filter_form %}
    </div>
{% endblock %}
{% block page_content %}
    <div id="dashboard">
        <div class="row">
            <div class="col-md-12">
                <div class="panel">
                    <div class="panel-heading">{% trans "Admissions and performance indicators" %}</div>
                    <div id="chartplaceholder" style="height: 465px"></div>
                </div>
            </div>
            {#            <div class="col-md-4" id="filter">#}
            {#                <!-- Extra space -->#}
            {#            </div>#}
        </div>
        <div class="row">
            <div class="col-md-6">
                <div class="panel">
                    <div class="panel-heading">
                        {% trans "Number of implementation sites" %}
                    </div>
                    <table class="table table-bordered" width="100%">
                        <thead>
                        <tr>
                            <th></th>
                            <th>{% trans "Active" %}</th>
                            <th>{% trans "Inactive" %}</th>
                            <th>{% trans "Total" %}</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for program in programs %}
                            <tr>
                                <td>{% trans program.description %}
                                    ({% trans program.code %})
                                </td>
                                <td>{{ program.active_site_count }}</td>
                                <td>{{ program.inactive_site_count }}</td>
                                <td>{{ program.reporting_site_count }}</td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
            {% if latest_global_data %}
                <div class="col-md-6">
                    <div class="panel">
                        <div class="panel-heading">{% trans "Low stock alerts" %}</div>
                        <div id="lowStockTable"></div>
                    </div>
                </div>
            {% endif %}
        </div>
        {% if latest_global_data %}
            <div class="row">
                <div class="col-md-6">
                    <div class="panel">
                        <div class="panel-heading">{% trans "Stock out alerts" %}</div>
                        <div id="reportTable"></div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="panel">
                        <div class="panel-heading">{% trans "Current reporting" %}</div>
                        <div id="messageTable"></div>
                    </div>
                </div>
            </div>
        {% endif %}
    </div>
{% endblock %}
{% block tail_script %}
    {% compress js %}
        <script src="{% static "underscore/underscore.js" %}"></script>
        <script src="{% static "stringjs/lib/string.js" %}"
                type="text/javascript"></script>
        <script src="{% static "tabler/lib/tabler/tabler.js" %}"
                type="text/javascript"></script>
        <script src="{% static "select2/select2.js" %}"
                type="text/javascript"></script>
        <script src="{% static "highcharts/highcharts.js" %}"
                type="text/javascript"></script>
        <script src="{% static "moment/moment.js" %}"
                type="text/javascript"></script>
    {% endcompress %}
    {% compress js %}
        <script src="{% static "js/filters.js" %}"
                type="text/javascript"></script>
        <script type="text/javascript">
            var messageTable, reportTable, lowStockTable;
            $(document).ready(function () {
                renderChart();
                {% if latest_global_data %}
                    messageTable = tabler.create([
                        {
                            field: 'text',
                            name: 'Text',
                            formatter: function (data) {
                                return S(data).truncate(32);
                            }
                        },
                        {
                            field: 'date',
                            name: 'Time',
                            formatter: function (data) {
                                return moment.unix(data).format('HH:mm:ss DD/MM/YYYY');
                            }
                        }
                    ], {
                        className: 'table table-striped table-hover table-bordered'
                    });
                    reportTable = tabler.create([
                        {field: 'items', name: 'Items'},
                        {field: 'path', name: 'Location'},
                        {field: 'site_id', name: 'Site ID'},
                        {
                            field: 'date',
                            name: 'Time',
                            formatter: function (data) {
                                return moment.unix(data).format('HH:mm:ss DD/MM/YYYY');
                            }
                        }
                    ], {
                        className: 'table table-striped table-hover table-bordered'
                    });

                    lowStockTable = tabler.create([
                        {field: 'item', name: 'Item'},
                        {field: 'path', name: 'Location'},
                        {field: 'site_id', name: 'Site ID'},
                        {
                            field: 'date',
                            name: 'Time',
                            formatter: function (data) {
                                return moment.unix(data).format('HH:mm:ss DD/MM/YYYY');
                            }
                        }
                    ], {
                        className: 'table table-striped table-hover table-bordered'
                    });

                    refresh();
                    window.setInterval(refresh, 120000);
                {% endif %}
            });

            function refresh() {
                $.getJSON("{% url 'api_dispatch_list' resource_name='messages' api_name='v1' %}", function (data) {
                    messageTable.load(data.objects);
                    messageTable.render();
                });
                $.getJSON("{% url 'api_dispatch_list' resource_name='stockouts' api_name='v1' %}", function (data) {
                    reportTable.load(data.objects);
                    reportTable.render();
                });
                $.getJSON("{% url 'api_dispatch_list' resource_name='low_stocks' api_name='v1' %}", function (data) {
                    lowStockTable.load(data.objects);
                    lowStockTable.render();
                });

                $('#messageTable').html(messageTable.$el);
                $('#reportTable').html(reportTable.$el);
                $('#lowStockTable').html(lowStockTable.$el);
            }

            // This script is released to the public domain and may be used, modified and
            // distributed without restrictions. Attribution not necessary but appreciated.
            // Source: http://weeknumber.net/how-to/javascript

            // Returns the ISO week of the date.
            Date.prototype.getWeek = function () {
                var date = new Date(this.getTime());
                date.setHours(0, 0, 0, 0);
                // Thursday in current week decides the year.
                date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
                // January 4 is always in week 1.
                var week1 = new Date(date.getFullYear(), 0, 4);
                // Adjust to Thursday in week 1 and count number of weeks from date to week1.
                return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000
                        - 3 + (week1.getDay() + 6) % 7) / 7);
            };

            // Returns the four-digit year corresponding to the ISO week of the date.
            Date.prototype.getWeekYear = function () {
                var date = new Date(this.getTime());
                date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
                return date.getFullYear();
            };

            function renderChart() {
                $.getJSON("{% url 'dashboard_chart' %}", function (dataSet) {
                    if (dataSet == null) {
                        var noticeDiv = document.createElement('div');
                        noticeDiv.className = 'hero-unit';

                        var noticeParagraph = document.createElement('p');
                        noticeParagraph.innerText = '{% trans "No data available" %}';

                        noticeDiv.appendChild(noticeParagraph);
                        $('#chartplaceholder').append(noticeDiv);
                        return;
                    }

                    Highcharts.dateFormats = {
                        W: function (timestamp) {
                            var date = new Date(timestamp);
                            return date.getWeek();
                        },
                        Z: function (timestamp) {
                            var date = new Date(timestamp);
                            return date.getWeekYear();
                        }
                    };

                    $('#chartplaceholder').highcharts({
                        chart: {
                            zoomType: 'xy'
                        },
                        colors: [
                            '#ffc1cc',
                            '#e32636',
                            '#000',
                            '#bd33a4',
                            '#ff8243'
                        ],
                        title: {
                            text: 'Performance indicators'
                        },
                        xAxis: {
                            type: 'datetime',
                            tickInterval: 3 * 7 * 24 * 36e5,
                            dateTimeLabelFormats: {
                                week: '%W/%Z'
                            },
                            startOfWeek: 0,  // Display Sunday dates
                            labels: {
                                align: 'right',
                                rotation: -45
                            }
                        },
                        yAxis: [{
                            title: {text: '# Patients'}
                        }, {
                            title: {text: '%'},
                            opposite: true,
                            min: 0,
                            max: 100
                        }],
                        tooltip: {
                            shared: true,
                            dateTimeLabelFormats: {
                                week: 'Week %W/%Z'
                            }
                        },
                        series: [{
                            name: 'Admissions',
                            type: 'column',
                            data: dataSet.Atot,
                            yAxis: 0
                        }, {
                            name: 'Death rate',
                            type: 'line',
                            data: dataSet.death_rate,
                            yAxis: 1,
                            tooltip: {valueSuffix: ' %'}
                        }, {
                            name: 'Defaulter rate',
                            type: 'line',
                            data: dataSet.defaulter_rate,
                            marker: {enabled: false},
                            yAxis: 1,
                            tooltip: {valueSuffix: ' %'}
                        }, {
                            name: 'Non-recovered rate',
                            type: 'line',
                            data: dataSet.referral_rate,
                            marker: {enabled: false},
                            yAxis: 1,
                            tooltip: {valueSuffix: ' %'},
                            dashStyle: 'longdash'
                        }, {
                            name: 'Transfer rate',
                            type: 'line',
                            data: dataSet.transfer_rate,
                            marker: {enabled: false},
                            yAxis: 1,
                            tooltip: {valueSuffix: ' %'},
                            dashStyle: 'shortdot'
                        }]
                    });
                });
            }
        </script>
    {% endcompress %}
{% endblock %}
