{% extends 'base.html' %}

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

{% block head %}
    <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>
        .tab-header {margin-left: 8px;}
        /* div {word-break: break-all;} */
        th {
            background-color: #ddd;
            text-align: left;
        }
        .blue {
            color: #409EFF;
            font-size: 30px;
        }
        .blue a{
            color: #409EFF;
            text-decoration: underline;
        }
        .green {
            color: #67c23a;
            font-size: 30px;
        }
    </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 %}
    history.pushState(null, '', window.location.pathname + location.search.replace('refresh_cache=True', 'refresh_cache='));
    {% endif %}

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


{% block body %}
<h3>PROJECT ({{ project }})<br>SPIDER ({{ spider }})</h3>

<div class="wrap collapse-wrap">
    <ul class="collapse">
        {% if url_utf8 %}
        <li>
            <div class="title">
                <h4>Log</h4>
                <i class="iconfont icon-right"></i>
            </div>
            <p><a class="link" href="{{ url_utf8 }}" onclick="showLoader();">{{ url_utf8 }}</a></p>
        </li>
        {% endif %}

        <li>
            <div class="title">
                <h4>Source</h4>
                <i class="iconfont icon-right"></i>
            </div>
            <p><a class="link" target="_blank" href="{{ url_source }}">{{ url_source }}</a></p>
        </li>
    </ul>
</div>

{% if refresh_url %}
<a id="refresh_button" class="button normal" href="{{ refresh_url }}" onclick="showLoader();">
Using cached version, click to refresh
</a>
{% endif %}

<div class="tab-wrap wrap">
    <ul class="tab tab-header clear-float">
        <li id="header_stats">Stats collection</li>
        {% if datas and datas[-1][1] %}
        <li id="header_charts">Progress visualization</li>
        {% endif %}
        <li id="header_logs">Logs categorization</li>
    </ul>
    <ul class="tab tab-content">
        <li id="content_stats">
            <div class="table vertical-table">
                <table>
                    <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>
                            <strong class="blue">
                            <a href="{{ url_utf8 }}">{{ finish_reason or "NOT found in log" }}</a>
                            </strong>
                        </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 }};

my$('#current_time').innerHTML = new Date();
setColor(30);
</script>


<script>
{% if refresh_url %}
setInterval(function() {
    var now_timestamp = Date.now() / 1000;
    var seconds = Math.ceil(now_timestamp - LAST_REFRESH_TIMESTAMP);
    my$('#refresh_button').innerHTML = "Cached " + seconds + " seconds ago, click to refresh";
    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);
        tabHeaders.forEach(function(el) {
            el.classList.remove('active');
        });
        target.classList.add('active');
        tabContents.forEach(function(el) {
            el.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'));
        }

        var tab = target.id.split('_')[1];
        if (location.search) {
            var kwargs = parseQueryString(location.search);
            if (kwargs.active_tab) {
                history.pushState(null, '', location.pathname + location.search.replace(/active_tab=\w+/i, 'active_tab=' + tab));
            } else {
                history.pushState(null, '', location.pathname + location.search.replace('?', '?active_tab=' + tab + '&'));
            }
        } else {
            history.pushState(null, '', location.pathname + '?active_tab=' + tab);
        }
    });
})();
</script>


<script>
// handle collapse components
(function () {
    var collapse = my$('.collapse');
    var titles = my$$('.collapse .title');
    var lis = my$$('.collapse li');
    titles.forEach(function(title) {
        title.addEventListener('click', function(e){
            var index = [].indexOf.call(titles, this);
            lis[index].classList.toggle('active');
        });
    });
})();
</script>
{% endblock %}
