{% extends 'timeseer.html' %}
{% from 'resources.html' import resource_breadcrumb %}
{% from 'macros.html' import alerter, info_popover, menu_back, progress_bar, visualize_score, visualize_series_name, visualize_split_kpi_score %}

{% macro compare(a, b) %}
<td>
    {% if a == b %}
    <span>=</span>
    {% elif a > b %}
    <a class="ts-table-link text-decoration-none"
       href="{{ url_for('.compare_evaluations', viewevaluationid=view_evaluation.db_id, compareviewevaluationid=compare_evaluation.db_id, sourcename=source_name) }}">
        <span class="text-danger">{{ b - a }}%</span>
    </a>
    {% else %}
    <a class="ts-table-link text-decoration-none"
       href="{{ url_for('.compare_evaluations', viewevaluationid=view_evaluation.db_id, compareviewevaluationid=compare_evaluation.db_id, sourcename=source_name) }}">
        <span class="text-success">+{{ b - a }}%</span>
    </a>
    {% endif %}
</td>
{% endmacro %}

{% block menu %}
{{ menu_back(url_for('home.home_page', sourcename=source_name)) }}
{% endblock %}

{% block breadcrumb %}
{{
    resource_breadcrumb([
        ("Data services", url_for('data_services.list_data_services', sourcename=source_name)),
        (view_evaluation.data_service_view.data_service.name, url_for('data_services.configure_data_service', dataservicename=view_evaluation.data_service_view.data_service.name, sourcename=source_name)),
        view_evaluation.data_service_view.series_set_name,
    ])
}}
{% endblock %}

{% block csp_style %}
'self' 'unsafe-inline'
{% endblock %}

{% block scripts %}
<script src="{{ url_for('static', filename='dist/charts.js') }}" nonce="{{ csp_nonce }}"></script>
{% endblock %}

{% block styles %}
<style nonce="{{ csp_nonce }}">
.ts-score-column {
    width: 5.5rem;
}

.ts-favorite-column {
    width: 16px;
}

#timeseries_source_score {
    max-width: 30rem;
    max-height: 20rem;
}

.ts-series-table {
    table-layout: fixed;
}
</style>
{% endblock %}

{% block main %}
<div class="offcanvas offcanvas-end" tabindex="-1" id="view-evaluation-select">
    <div class="offcanvas-header">
        <h3 class="offcanvas-title h5">Evaluations for "{{ view_evaluation.data_service_view.series_set_name }}" ({{ view_evaluation.data_service_view.data_service.name }})</h3>
        <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
    </div>
    <div class="offcanvas-body">
        <form>
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <input type="hidden" name="dataserviceviewid" value="{{ view_evaluation.data_service_view.db_id }}">
            <div class="row align-items-center gx-2">
                {% if view_evaluations|count > 0 %}
                <div class="col-md-auto">
                    <div class="btn-group ts-dropdown-select-button">
                        <a class="btn border border-secondary dropdown-toggle"
                            href="#"
                            role="button"
                            id="viewSelectionDropdown"
                            data-bs-toggle="dropdown"
                            aria-haspopup="true"
                            aria-expanded="false">
                        </a>
                        <div class="dropdown-menu" aria-labelledby="viewSelectionDropdown">
                            <button type="submit"
                                    class="dropdown-item ts-dropdown-action"
                                    formmethod="POST"
                                    formaction="{{ url_for('.remove_view_evaluations', sourcename=source_name) }}"
                                    >
                                    Remove selected
                            </button>
                        </div>
                    </div>
                </div>
                {% endif %}
            </div>
            <table class="ts-table ts-table-checkbox table table-borderless mt-3" data-ts-target="viewSelectionDropdown">
                <thead class="thead-secondary">
                    <th scope="col">
                        {% if view_evaluations|count > 0 %}
                        <input class="form-check-input" type="checkbox">
                        {% endif %}
                    </th>
                    <th scope="col">Evaluation date</th>
                </thead>
                <tbody>
                    {% for evaluation in view_evaluations %}
                    <tr class="border-bottom">
                        <td>
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" name="viewevaluationids" value="{{ evaluation.db_id }}">
                            </div>
                        </td>
                        <td>
                            {% if evaluation is not none and evaluation.db_id != view_evaluation.db_id %}
                            <a class="ts-table-link text-dark text-decoration-none" href="{{ url_for('.show_data_service_view_evaluation', viewevaluationid=evaluation.db_id, sourcename=source_name) }}">
                                {{ evaluation.evaluation_date|ts_datetime }}
                            </a>
                            {% else %}
                            {{ evaluation.evaluation_date|ts_datetime }}
                            {% endif %}
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </form>
    </div>
</div>

<div class="ts-section py-3 my-3">
    <div class="row align-items-center">
        <div class="col">
            <h2 class="h4">Results for "{{ view_evaluation.data_service_view.series_set_name }}" ({{ view_evaluation.data_service_view.data_service.name }})</h2>
        </div>
        <div class="col-lg-auto">
            <form>
                <input type="hidden" name="viewevaluationid" value="{{ view_evaluation.db_id }}">
                <div class="btn-toolbar" role="group">

                    <a class="btn btn-secondary me-2" href="{{ url_for('.show_multivariate_statistics', sourcename=source_name, viewevaluationid=view_evaluation.db_id) }}">
                        Statistics
                    </a>
                    <div class="btn-group">
                        <a class="btn btn-primary" href="{{ url_for('.list_evaluations', sourcename=source_name, viewevaluationid=view_evaluation.db_id) }}">
                            History
                        </a>
                        <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false">
                            <span class="visually-hidden">Toggle Dropdown</span>
                        </button>
                        <ul class="dropdown-menu">
                            <li>
                                <a class="dropdown-item" href="{{ url_for('.open_report', viewevaluationid=view_evaluation.db_id, sourcename=source_name) }}" target="_blank">
                                    Open print report
                                    <sup>{{ bootstrap_icon('box-arrow-up-right') }}</sup>
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="ts-section pb-3">
    <div class="row align-items-center">
        <div class="col-md-5 ge-2">
            <div class="row align-items-center">
                <div class="fw-bold col-xxl-auto">Date range</div>
                <small class="text-muted col-xxl">
                    {% if view_evaluation.data_service_view.data_service.time_range.has_no_time_range() is true %}
                        -
                    {% else %}
                    {{ view_evaluation.data_service_view.data_service.time_range.start_date|ts_datetime }}
                    {{ bootstrap_icon('arrow-right-short', 'text-dark') }}
                    {{ view_evaluation.data_service_view.data_service.time_range.end_date|ts_datetime }}
                    {% endif %}
                </small>
            </div>
        </div>
        <div class="col-md ge-2">
            <div class="row align-items-center">
                <div class="fw-bold col-xxl-auto">Evaluation</div>
                <div class="col-xxl">
                    <a class="btn btn-sm bg-light text-muted text-nowrap"
                        href="#view-evaluation-select"
                        data-bs-toggle="offcanvas">
                        {{ view_evaluation.evaluation_date|ts_datetime }}
                        {{ bootstrap_icon('three-dots-vertical') }}
                    </a>
                </div>
            </div>
        </div>
        <div class="col-md">
            <div class="row align-items-center">
                {% if other_views|count > 1 %}
                <div class="fw-bold col-xxl-auto">Series sets</div>
                <div class="col-xxl">
                    <a class="btn dropdown-toggle btn-sm bg-light text-muted"
                        href="#"
                        role="button"
                        id="editSeriesSetDropdownLink"
                        data-bs-toggle="dropdown"
                        aria-haspopup="true"
                        aria-expanded="false">
                        {{ view_evaluation.data_service_view.series_set_name }}
                    </a>
                    <div class="dropdown-menu" aria-labelledby="editSeriesSetDropdownLink">
                        {% for view in other_views|sort(attribute='series_set_name') %}
                            {% if view != view_evaluation.data_service_view %}
                            <a class="dropdown-item" href="{{ url_for('.show_data_service_view', viewid=view.db_id, sourcename=source_name) }}">{{ view.series_set_name }}</a>
                            {% else %}
                            <a class="dropdown-item active">{{ view.series_set_name }}</a>
                            {% endif %}
                        {% endfor %}
                    </div>
                </div>
                {% else %}
                <div class="fw-bold col-xxl-auto">Series set</div>
                <div class="col-xxl">
                    <a class="btn text-muted btn-sm bg-light pe-none col-lg">
                        {{ view_evaluation.data_service_view.series_set_name }}
                    </a>
                </div>
                {% endif %}
            </div>
        </div>
        <div class="col-md row align-items-center">
            <div class="fw-bold col-xxl-auto">Display</div>
            <div class="dropdown col-sm-auto">
                <button type="button"
                        class="btn btn-sm btn-secondary dropdown-toggle"
                        data-bs-toggle="dropdown"
                        aria-haspopup="true"
                        aria-expanded="false">
                    Scores
                </button>
                <div class="dropdown-menu dropdown-menu-end">
                    <a class="dropdown-item {% if compare_to is none %}active{% endif %}"
                       href="{{ url_for ('.show_data_service_view_evaluation_counts', sourcename=source_name, viewevaluationid=view_evaluation.db_id, compareTo=compare_evaluation.db_id if compare_evaluation is not none else none) }}">
                       Series counts
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>


{% if analysis_state.is_defined() and not analysis_state.is_completed() %}
    <div class="pt-3 my-3">
        {% call progress_bar(analysis_state, url_for('.get_view_evaluation_analysis_state', dataserviceviewevaluationid=view_evaluation.db_id), label='calculations', empty_is_pending=True) %}
            Analysis
        {% endcall %}
    </div>
{% else %}


<div class="pt-3 my-3">
    <div class="card shadow-sm">
        <div class="card-header">
            <div class="row align-items-center justify-content-between">
                <h3 class="col-sm-6 mb-0 h5">Quality KPI scores</h3>
                {% if kpi_scores|count > 0 and view_evaluations|count > 2 %}
                <div class="dropdown col-sm-auto">
                    <button type="button"
                            class="btn btn-sm btn-secondary dropdown-toggle"
                            data-bs-toggle="dropdown"
                            aria-haspopup="true"
                            aria-expanded="false">
                        Compare to
                    </button>
                    <div class="dropdown-menu dropdown-menu-end">
                        <a class="dropdown-item {% if compare_to is none %}active{% endif %}"
                           {% if compare_to is not none %}
                           href="{{ url_for ('.show_data_service_view_evaluation', sourcename=source_name, viewevaluationid=view_evaluation.db_id) }}"
                           {% endif %}>
                           Previous
                        </a>
                        <div class="dropdown-divider"></div>
                        <h6 class="dropdown-header">Evaluations</h6>
                        {% for evaluation in view_evaluations|sort(attribute='evaluation_date')|reverse if evaluation.db_id != view_evaluation.db_id %}
                        <a class="dropdown-item {% if compare_evaluation.db_id == evaluation.db_id %}active{% endif %}"
                           {% if compare_evaluation.db_id == evaluation.db_id %}
                           {% elif previous_evaluation.db_id == evaluation.db_id %}
                           href="{{ url_for('.show_data_service_view_evaluation', sourcename=source_name, viewevaluationid=view_evaluation.db_id) }}"
                           {% elif compare_evaluation.db_id != evaluation.db_id %}
                           href="{{ url_for('.show_data_service_view_evaluation', sourcename=source_name, compareTo=evaluation.db_id, viewevaluationid=view_evaluation.db_id) }}"
                           {% endif %}>
                            {{ evaluation.evaluation_date|ts_datetime }}
                        </a>
                        {% endfor %}
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
        {% if kpi_scores|count > 0 %}
        <div class="row gx-0">
            {% if kpi_scores|count > 2 %}
            <div class="col border-end d-flex justify-content-center">
                <div id='timeseries_source_score'></div>
            </div>
            {% endif %}
            <div class="col">
                <table class="ts-table table table-borderless">
                    <thead class="table-secondary">
                        <tr class="border-bottom">
                            <th scope="col" colspan="2">
                                <a class="text-reset" href="{{ url_for('kpi_sets.configure_kpi_set', kpisetname=kpi_set.name, sourcename=source_name) }}"
                                   target="_blank">
                                    {{ kpi_set.name }} <sup>{{ bootstrap_icon('box-arrow-up-right') }}</sup>
                                </a>
                            </th>
                            <th scope="col">Score</th>
                            <th scope="col">Evolution</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for entry in kpi_set_entries|sort(attribute='kpi.name') %}
                        {% set kpi = entry.kpi %}
                        <tr class="border-bottom">
                            <td class="ts-favorite-column">
                                {% if entry.favorite %}
                                {{ bootstrap_icon('star-fill', 'text-primary icon') }}
                                {% endif %}
                            </td>
                            <th scope="row">
                                <a class="ts-table-link text-decoration-none text-dark" href="{{ url_for('.kpi_report', kpi=kpi.name, sourcename=source_name, viewevaluationid=view_evaluation.db_id) }}">
                                    {{ kpi.name }}
                                </a>
                            </th>
                            {% if kpi.name in kpi_scores %}
                            {{ visualize_score(kpi_scores[kpi.name]) }}
                            {% else %}
                            <td>-</td>
                            {% endif %}
                            {% if kpi.name in kpi_scores and kpi.name in comparison_kpi_scores %}
                            {{ compare(comparison_kpi_scores[kpi.name], kpi_scores[kpi.name]) }}
                            {% else %}
                            <td>-</td>
                            {% endif %}
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
        {% else %}
        <div class="text-muted text-center p-1">
            No results to display.
        </div>
        {% endif %}
    </div>
</div>

{% if view_evaluation.data_service_view.data_service.time_range.has_no_time_range() is false %}
<div class="mt-4" id="bad-actor-visualization-container">
    <div class="card shadow-sm">
        <div class="card-header">
            <h3 class="mb-0 h5">Bad actor visualization</h3>
        </div>
        <div class="row gx-0">
        <div id="bad-actor-visualization">
            <div class="alert alert-primary mt-2">
                <div class="row align-items-center">
                    <div class="col">
                        Loading chart...
                    </div>
                    <div class="col-auto">
                        <div class="spinner-border text-primary" role="status"></div>
                    </div>
                </div>
            </div>
        </div>
        </div>
    </div>
</div>
{% endif %}


<div class="mt-4">
    <div class="row">
        {% for kpi, scores in kpi_score_scores|dictsort %}
        <div class="col-md-6 mt-4">
            <div class="card shadow-sm h-100 ">
                <div class="card-header">
                    <h3 class="mb-0 h5">{{ kpi|capitalize }}</h3>
                </div>
                <table class="ts-card-table table table-sm table-borderless">
                    <thead class="table-secondary">
                        <tr class="border-bottom">
                            <th scope="col">Name</th>
                            <th scope="col" class="ts-score-column">Score</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% if scores|count > 0 %}
                        {% for score in scores|sort(attribute="weight", reverse=True) %}
                        <tr class="border-bottom">
                            <th scope="row">
                                {% if score.metadata.name in multivariate_checks %}
                                <span class="text-dark fw-normal text-decoration-none">
                                    {{ score.metadata.name|capitalize }}
                                </span>
                                {% else %}
                                <a class="ts-table-link text-dark fw-normal text-decoration-none" href="{{ url_for('.score_event_frames', sourcename=source_name, kpi=kpi, score=score.metadata.name, viewevaluationid=view_evaluation.db_id) }}">
                                    {{ score.metadata.name|capitalize }}
                                </a>
                                {% endif %}
                                {{ info_popover(score.metadata.short_help_text) }}
                            </th>
                            {{ visualize_score(score.score) }}
                        </tr>
                        {% endfor %}
                        {% endif %}
                    </tbody>
                </table>
                {% if scores|count == 0 %}
                <div class="text-muted text-center p-1">
                    No results to display.
                </div>
                {% endif %}
            </div>
        </div>
        {% endfor %}
    </div>
</div>


<div class="my-4">
    <div class="card shadow-sm">
        <div class="card-header">
            <div class="row align-items-center justify-content-between">
                <h3 class="col-sm-8 mb-0 h5">Worst scoring series</h3>
                {% if worst_series|count > 0 %}
                <form class="col-sm-auto" action="{{ url_for('.series_score_report') }}">
                    <input type="hidden" name="viewevaluationid" value="{{ view_evaluation.db_id }}">
                    {% if source_name %}
                    <input type="hidden" name="sourcename" value="{{ source_name }}">
                    {% endif %}
                    <button type="submit" class="btn btn-sm btn-secondary">Display all</button>
                </form>
                {% endif %}
            </div>
        </div>

        {% if worst_series|count > 0 %}
        <table class="ts-card-table ts-series-table table table-sm table-borderless table-hover">
            <thead class="table-secondary">
                <tr class="border-bottom">
                    <th scope="col">Series name</th>
                    <th scope="col">Score</th>
                </tr>
            </thead>
            <tbody>
                {% for series, score in worst_series.items() %}
                <tr class="border-bottom">
                    <th scope="row">
                        <a class="ts-table-link text-dark fw-normal text-decoration-none" href="{{ url_for('data_services.show_event_frames', seriesid=series.series_id, viewevaluationid=view_evaluation.db_id) }}"
                        class="text-break">
                            {{ visualize_series_name(series.name) }}
                        </a>
                    </th>
                    {{ visualize_score(score) }}
                </tr>
                {% endfor %}
            </tbody>
        </table>
        {% else %}
        <div class="text-muted text-center p-1">
            No results to display.
        </div>
        {% endif %}
    </div>
</div>

<script nonce="{{ csp_nonce }}">
    {% if kpi_scores|count > 2 %}
    {% include 'scripts/kpi-scores-data-service.js' %}
    {% endif %}

    {% if view_evaluation.data_service_view.data_service.time_range.has_no_time_range() is false %}
    {% include 'scripts/flow-bad-actor-visualization.js' %}

    fetch('{{ url_for(".bad_actors_data") }}?' + new URLSearchParams({
        viewevaluationid: '{{ view_evaluation.db_id }}',
        includelinks: true,
    }))
        .then(function (response) {
            if (response.status === 200) {
                return response.json();
            } else if (response.status === 408 || response.status === 504) {
                throw new Error('Timeout while loading bad actors visualization data.')
            } else {
                throw new Error('Failed to load bad actors visualization data.')
            }
        }).then(function (data) {
            var chartEl = document.getElementById('bad-actor-visualization');
            while (chartEl.firstChild) {
                chartEl.removeChild(chartEl.lastChild);
            }
            if (data.length == 0) {
            document.getElementById('bad-actor-visualization').innerHTML = `
                    <div class="text-muted text-center p-1">No results to display.</div>
            `
            } else {
                plotBadActors(data);
            }
        }, function (exception) {
            document.getElementById('bad-actor-visualization').innerHTML = `
                <div class="alert alert-danger mt-2">${exception.message}</div>
            `;
        });
    {% endif %}
</script>
{% endif %}
{% endblock %}

{% block scripts_bottom %}
<script src="{{ url_for('static', filename='dist/data-services.js') }}" nonce="{{ csp_nonce }}"></script>
{% endblock %}
