{% extends 'base_mobileui.html' %}

{% block title %}stats{% endblock %}

{% block head %}
    <!-- <meta name="viewport" content=""> -->
    <link rel="stylesheet" type="text/css" href="{{ static_css_stats }}">
    <script type="text/javascript" src="{{ static_js_stats }}"></script>
    <script type="text/javascript" src="{{ static_js_echarts_min }}"></script>
    <style>
    table {
        border-collapse: collapse;
        width: 100%;
    }
    /* div{word-break: break-all;} */
    table th {
        background-color: #faf8e9;
        font-size: 14px;
        padding-left: 12px;
        padding-right: 12px;
        text-align: right;
        word-break: keep-all;
    }
    table td{
        padding-left: 12px;
        padding-right: 12px;
        text-align: center;
    }
    table tr:nth-child(1) td {word-break: break-all;}
    table tr:nth-child(2) td {word-break: break-all;}
    table tr:nth-child(3) td {word-break: break-all;}
    .green {
        color: #67c23a;
        font-size: 20px;
    }
    #content_logs {padding: 10px 0;}
    pre {padding: 0 10px;}
    </style>
{% endblock %}

{% block loader %}
<div class="loader" style="display: block;" onclick="hideLoader();"></div>

<script>
window.onload = function(){
    // Clear refresh_cache=True in href after clicking refresh cache button
    {% if refresh_url_mobileui %}
    history.pushState(null, '', window.location.pathname + location.search.replace('refresh_cache=True', 'refresh_cache='));
    {% endif %}

    hideLoader();
};
</script>
{% endblock %}


{% block neck %}
<a class="button normal" href="javascript:;" onclick="forceLoader('{{ url_dashboard_mobile }}')">Dashboard</a>
<a class="button warning" href="javascript:;" onclick="forceLoader('{{ url_utf8_mobile }}')">Log</a>
{% if refresh_url_mobileui %}
<a id="refresh_button" class="button normal" href="javascript:;" onclick="forceLoader('{{ refresh_url_mobileui }}');">Cached</a>
{% endif %}
{% endblock %}


{% block body %}
<div class="tab-wrap wrap">
    <ul class="tab tab-header clear-float">
        <li id="header_stats">Stats</li>
        {% if datas and datas[-1][1] %}
        <li id="header_charts">Charts</li>
        {% endif %}
        <li id="header_logs">Logs</li>
    </ul>

    <ul class="tab tab-content">
        <li id="content_stats">
            <div class="table vertical-table">
                <table border="1">
                    <tr><th>project</th><td>{{ project }}</td></tr>
                    <tr><th>spider</th><td>{{ spider }}</td></tr>
                    <tr><th>job</th><td>{{ job }}</td></tr>
                    <tr><th>start_time</th><td>{{ first_log_time }}</td></tr>
                    <tr><th>latest_log_time</th><td>{{ latest_log_time }}</td></tr>
                    <tr><th>elasped</th><td>{{ elasped }}</td></tr>
                    <tr>
                        <th>finish_reason</th>
                        <td><a class="link" href="{{ url_utf8_mobile }}">
                            <strong style="font-size: 20px;">{{ finish_reason or "NOT found in log" }}</strong>
                            </a>
                        </td>
                    </tr>

                    <tr><th>log_critical_count</th><td id="log_critical_count">{{ log_critical_count }}</td></tr>
                    <tr><th>log_error_count</th><td id="log_error_count">{{ log_error_count }}</td></tr>
                    <tr><th>log_warning_count</th><td id="log_warning_count">{{ log_warning_count }}</td></tr>
                    <tr><th>log_redirect_count</th><td id="log_redirect_count">{{ log_redirect_count }}</td></tr>
                    <tr><th>log_retry_count</th><td id="log_retry_count">{{ log_retry_count }}</td></tr>
                    <tr><th>log_ignore_count</th><td id="log_ignore_count">{{ log_ignore_count }}</td></tr>

                    <tr><th>crawled_pages</th><td><strong class="green">{{ crawled_pages }}</strong></td></tr>
                    <tr><th>scraped_items</th><td><strong class="green">{{ scraped_items }}</strong></td></tr>
                    <tr><th>latest_crawl</th><td id="latest_crawl"></td></tr>
                    <tr><th>latest_scrape</th><td id="latest_scrape"></td></tr>
                    <tr><th>latest_log</th><td id="latest_log"></td></tr>
                    <tr><th>current_time</th><td id="current_time"></td></tr>
                </table>
            </div>
        </li>

        {% if datas and datas[-1][1] %}
        <li id="content_charts">
            <div id="chart_total" style="width: 100%; height: 400px;"></div>
            <div id="chart_minute" style="width: 100%; height: 400px;"></div>
        </li>
        {% endif %}

        <li id="content_logs">
            <div class="wrap collapse-wrap">
                <h3 style="color: #409EFF;">cat logs</h3>
                <ul class="collapse">
                    <li>
                        <div class="title">
                            <h4>head -50</h4>
                            <i class="iconfont icon-right"></i>
                        </div>
                        <pre>{{ head_lines }}</pre>
                    </li>
                   <li>
                        <div class="title">
                            <h4>tail -50</h4>
                            <i class="iconfont icon-right"></i>
                        </div>
                        <pre>{{ tail_lines }}</pre>
                    </li>
                </ul>
            </div>

            <div class="wrap collapse-wrap">
                <ul class="collapse">
                    <h3 style="color: red;">WARNING+</h3>
                {% for item in re_matches[:3] %}
                    {% if not item['count'] %}
                    {% else %}
                    <li>
                        <div class="title">
                            <h4>
                                <div style="width: 200px; display: inline-block;">{{ item['log_title'] }}</div>
                                {{ item['count'] }} in total
                            </h4>
                            <i class="iconfont icon-right"></i>
                        </div>

                        {% for line in item['lines'] %}
                        <pre>{{ line }}</pre>
                        {% endfor %}
                    </li>
                    {% endif %}
                {% endfor %}
                </ul>
            </div>

            <div class="wrap collapse-wrap">
                <ul class="collapse">
                    <h3 style="color: orange;">INFO</h3>

                {% for item in re_matches[3:] %}
                    {% if not item['count'] %}
                    {% else %}
                    <li>
                        <div class="title">
                            <h4>
                                <div style="width: 200px; display: inline-block;">{{ item['log_title'] }}</div>
                                {{ item['count'] }} in total
                            </h4>
                            <i class="iconfont icon-right"></i>
                        </div>

                        {% for line in item['lines'] %}
                        <pre>{{ line }}</pre>
                        {% endfor %}
                    </li>
                    {% endif %}
                {% endfor %}
                </ul>
            </div>

            <div class="wrap collapse-wrap">
                <ul class="collapse">
                    <h3 style="color: #67c23a;">DEBUG</h3>

                {% for title, line in latest_matches %}
                    {% if not line %}
                    {% else %}
                    <li>
                        <div class="title">
                            <h4>{{ title }}</h4>
                            <i class="iconfont icon-right"></i>
                        </div>
                        <pre>{{ line }}</pre>
                    </li>
                    {% endif %}
                {% endfor %}
                </ul>
            </div>
        </li>
    </ul>
</div>


<script>
var latest_crawl_timestamp = {{ latest_crawl_timestamp }};
var latest_scrape_timestamp = {{ latest_scrape_timestamp }};
var latest_log_timestamp = {{ latest_log_timestamp }};

const LAST_REFRESH_TIMESTAMP = {{ last_refresh_timestamp }};
const LAST_LOG_ALERT_SECONDS = {{ LAST_LOG_ALERT_SECONDS }};

{% if datas and datas[-1][1] %}
var id_of_tabs = new Array('table', 'chart', 'logs');
{% else %}
var id_of_tabs = new Array('table', 'logs');
{% endif %}

//my$('#current_time').innerHTML = new Date();
var now = new Date();
now.setMinutes(now.getMinutes()-now.getTimezoneOffset());
my$('#current_time').innerHTML = now.toISOString().slice(0,19).replace(/T/g, " ");
setColor(20);
</script>


<script>
{% if refresh_url_mobileui %}
setInterval(function() {
    var now_timestamp = Date.now() / 1000;
    var seconds = Math.ceil(now_timestamp - LAST_REFRESH_TIMESTAMP);
    my$('#refresh_button').innerHTML = seconds + "s ago";
    if(seconds > LAST_LOG_ALERT_SECONDS) {
        my$('#refresh_button').className = "button danger";
    } else {
        my$('#refresh_button').className = "button safe";
    }
}, 1000);
{% endif %}
</script>


{% if datas and datas[-1][1] %}
<script>
var datas = {{ datas|safe }};

var chartsArr = [{
    dom: my$('#chart_total'),
    echart: echarts.init(my$('#chart_total')),
    data: datas,
    title: 'count / total',
    label1: 'pages',
    index1: 1,
    label2: 'items',
    index2: 3
}, {
    dom: my$('#chart_minute'),
    echart: echarts.init(my$('#chart_minute')),
    data: datas,
    title: 'count / minute',
    label1: 'pages / minute',
    index1: 2,
    label2: 'items / minute',
    index2: 4
}]

chartsArr.forEach(function(chart) {
    draw(chart.echart, chart.data, chart.title, chart.label1, chart.index1, chart.label2, chart.index2)
    chart.dom.addEventListener('resize', function() {
        chart.echart.resize({ width: chart.dom.clientWidth })
    })
})

window.addEventListener('optimizedResize', function() {
    if (chartsArr[0].dom) {
        chartsArr.forEach(function(chart) {
            //console.log(chart)
            chart.dom.dispatchEvent(new Event('resize'))
        })
    }
})
</script>
{% endif %}


<script>
// tab switcher
(function() {
    var kwargs = parseQueryString(location.search);
    var active_tab = kwargs.active_tab || 'stats';
    if (my$('#header_'+active_tab)) {
        my$('#header_'+active_tab).classList.add('active');
        my$('#content_'+active_tab).classList.add('active');
    } else {
        my$('#header_stats').classList.add('active');
        my$('#content_stats').classList.add('active');
    }
    if (my$('#chart_total')) {
        my$('#chart_total').dispatchEvent(new Event('resize'));
        my$('#chart_minute').dispatchEvent(new Event('resize'));
    }


    var index = -1;
    var tabHeaders = my$$('.tab-header>li');
    var tabContents = my$$('.tab-content>li');
    my$('.tab-header').addEventListener('click', function(e) {
        var target = e.target;
        //console.log(target.id);
        if (target.tagName.toLowerCase() !== 'li') return;
        index = Array.prototype.indexOf.call(tabHeaders, target);
        for(var i = 0 ; i < tabHeaders.length; i++) {
            tabHeaders[i].classList.remove('active');
        }
        target.classList.add('active');
        for(var i = 0 ; i < tabContents.length; i++) {
            tabContents[i].classList.remove('active');
        }
        tabContents[index].classList.add('active');

        // When switch to echarts tab
        if (my$('#chart_total')) {
            my$('#chart_total').dispatchEvent(new Event('resize'));
            my$('#chart_minute').dispatchEvent(new Event('resize'));
        }

        history.pushState(null, '', location.pathname + "?ui=mobile&active_tab=" + target.id.split('_')[1]);
    });
})();
</script>




<script>
// handle collapse components
(function () {
    var collapse = my$('.collapse');
    var titles = my$$('.collapse .title');
    var lis = my$$('.collapse li');

    //https://stackoverflow.com/questions/32027935/addeventlistener-is-not-a-function-why-does-this-error-occur
    //for(idx in titles){
        //title = titles[idx];
    for(var i = 0 ; i < titles.length; i++) {
        titles[i].addEventListener('click', function(e){
            var index = [].indexOf.call(titles, this);
            lis[index].classList.toggle('active');
        });
    }
})();
</script>

{% endblock %}
