{% extends 'portal.html'%}
{% block header %}
<link rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/css/bootstrap-select.min.css"
    integrity="sha256-VMPhaMmJn7coDSbzwqB0jflvb+CDnoAlfStC5RogOQo=" crossorigin="anonymous" />
{% endblock %}
{% block javascript %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/js/bootstrap-select.min.js"
    integrity="sha256-QOE02Glo1C1gHzP96JOaxyIMt4XSFv/exZaYLY4dwO0=" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bokeh/3.3.4/bokeh.min.js"
    integrity="sha512-FdxCNfGfSXQtoNpQPgWbCP02ZJzQxaPlcMstU8hjk8m47efRnJ46tto1rew4aaC5XxqNSPoqfrxqRcaRE8iCmw==" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bokeh/3.3.4/bokeh-gl.min.js"
    integrity="sha512-ZyG5gFgPuDF/g5J/hbkq6o/sm82U/1j4lfheVheYfugvibXaMiuc20gsRqwr00QkZvfOJIS66LQUMYp6zgnpAQ==" crossorigin="anonymous">
</script>
<script>
    $(document).ready(function () {
        //Generate view data button url on population select change
        $("#population").change(function () {
            var viewDataButton = $("#view-data-button");
            viewDataButton.attr("href", viewDataButton.data("base-href").replace("selected", $(this).val()));
        });
        //Load population data
        var populationHttpRequest = new XMLHttpRequest();
        populationHttpRequest.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {//OK Response
                var json = JSON.parse(this.responseText);
                if (json.name.length == 0) $("#request-error").text("No population details found").parent().removeClass("d-none");
                else {
                    //Start Date
                    var timestampConvertEndpoint = '{{ url_for("timekeeper.convert_nanoseconds", nanoseconds=0, unit="milliseconds") }}';
                    var startTimestampConvertHttpRequest = new XMLHttpRequest();
                    startTimestampConvertHttpRequest.onreadystatechange = function () {
                        if (this.readyState == 4 && this.status == 200) {
                            var date = new Date(parseInt(this.responseText));
                            $("input[name='start-date']").val(date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, "0") + "-" + String(date.getDate()).padStart(2, "0"));
                            $("input[name='start-time']").val(String(date.getHours()).padStart(2, '0') + ":" + String(date.getMinutes()).padStart(2, '0'));
                        }
                    }
                    startTimestampConvertHttpRequest.open("GET", timestampConvertEndpoint.replace("0", json.start), true);
                    startTimestampConvertHttpRequest.send();
                    //End Date                    
                    var endTimestampConvertHttpRequest = new XMLHttpRequest();
                    endTimestampConvertHttpRequest.onreadystatechange = function () {
                        if (this.readyState == 4 && this.status == 200) {
                            var date = new Date(parseInt(this.responseText));
                            $("input[name='end-date']").val(date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, "0") + "-" + String(date.getDate()).padStart(2, "0"));
                            $("input[name='end-time']").val(String(date.getHours()).padStart(2, '0') + ":" + String(date.getMinutes()).padStart(2, '0'));
                        }
                    }
                    endTimestampConvertHttpRequest.open("GET", timestampConvertEndpoint.replace("0", json.end), true);
                    endTimestampConvertHttpRequest.send();
                    //Channels
                    var selectedChannels = {{ channels|safe }};
                    var sortedTypes = json.types.sort((a, b) => {
                        if (a.name > b.name) return 1;
                        else if (a.name < b.name) return -1;
                        else return 0;
                    });
                    var channelSelect = $("select[name='channels']");
                    for (var i = 0; i < json.types.length; i++) {
                        var options = "";
                        var sortedChannels = sortedTypes[i].channels.sort((a, b) => {
                            if (a.name > b.name) return 1;
                            else if (a.name < b.name) return -1;
                            else return 0;
                        });
                        for (var j = 0; j < sortedChannels.length; j++) {
                            var selected = false;
                            for (var k = 0; k < selectedChannels.length; k++) {
                                if (sortedChannels[j].name != selectedChannels[k]) continue;
                                selected = true;
                                break;
                            }
                            options += "<option" + ((selected) ? " selected" : "") + " value='" + sortedChannels[j] + "'>" + sortedChannels[j] + "</option>";
                        }
                        channelSelect.append("<optgroup label='" + sortedTypes[i].name + ((typeof sortedTypes[i].unit !== typeof undefined) ? " (" + sortedTypes[i].unit + ")" : "") + "'>" + options + "</optgroup>");
                    }
                }
                $("form .form-control").removeAttr("disabled");
                $("form .selectpicker").selectpicker("refresh");
                $("#request-loading").removeAttr("disabled").children(".spinner-border").addClass("d-none");
            } else if (this.readyState == 1) {//Connection Established
                $("form .form-control").attr("disabled", true);
                $("#request-loading").attr("disabled", true).children(".spinner-border").removeClass("d-none");
            } else if (this.readyState == 4) {//Error Status
                $("#request-loading").removeAttr("disabled").children(".spinner-border").addClass("d-none");
                $("#request-error").text("Error " + this.status + ": " + this.statusText).parent().removeClass("d-none");
            }
        }
        populationHttpRequest.open("GET", '{{ url_for("autostat.population_details", population=population) }}', true);
        populationHttpRequest.setRequestHeader("Accept", "application/json");
        populationHttpRequest.send();
        //Document submit
        $(document).submit(function () {
            $("#request-loading").attr("disabled", true).children(".spinner-border").removeClass("d-none");
            return true;
        });
    });
</script>
{{ scripts|safe if scripts else '' }}
{% endblock %}
{% block title %}{{ population }}{% endblock %}
{% block title_call_to_action %}
<div class="input-group">
    <select id="population" name="population" class="form-control">
        {% for item in populations %}
        <option {{ "selected" if item == population else "" }}>
            {{ item }}
        </option>
        {% endfor %}
    </select>
    <div class="input-group-append">
        <a id="view-data-button" data-base-href='{{ url_for("autostat.population_statistics", population="selected") }}'
            href='{{ url_for("autostat.population_statistics", population=population) }}' class="btn btn-outline-info">
            Switch
        </a>
    </div>
</div>
{% endblock %}
{% block content %}
<form method="POST">
    <div class="row mb-2">
        <!-- Start Date -->
        <div class="col-md-12 col-lg-6 mb-2 mb-lg-0">
            <div class="input-group">
                <div class="input-group-prepend">
                    <span class="input-group-text bg-light border-light">
                        Start Date
                    </span>
                </div>
                <input name="start-date" type="date" class="form-control border-light">
                <input name="start-time" type="time" value="00:00" class="form-control flex-grow-0 w-25 border-light">
            </div>
        </div>
        <!-- End Date -->
        <div class="col-md-12 col-lg-6">
            <div class="input-group">
                <div class="input-group-prepend">
                    <span class="input-group-text bg-light border-light">
                        End Date
                    </span>
                </div>
                <input name="end-date" type="date" class="form-control border-light">
                <input name="end-time" type="time" value="00:00" class="form-control flex-grow-0 w-25 border-light">
            </div>
        </div>
    </div>
    <div class="row mb-2">
        <!-- Channels -->
        <div class="col-md-12 col-lg-8">
            <select name="channels" multiple title="Channel Names" data-live-search="true"
                class="form-control selectpicker">
            </select>
        </div>
        <!-- Generate Button -->
        <div class="col-lg-4">
            <button id="request-loading" type="submit" class="btn btn-block btn-outline-success">
                <div class="spinner-border spinner-border-sm text-secondary mr-1 d-none" role="status">
                </div>
                Generate statistics
            </button>
        </div>
    </div>
</form>
<div class="mt-2 {{ 'd-none' if error is none else '' }}">
    <div id="request-error" class="alert alert-danger" role="alert">
        {{ error }}
    </div>
</div>
<!-- Figure -->
<div class="mt-3">
    {% if figure %}
        <h2 class="text-secondary border-bottom border-light mb-2">Normalised Data</h2>
        {{ figure|safe }}
    {% endif %}
</div>
<!-- Key -->
<div class="mt-3">
    {% if key|length > 0 %}
        <h2 class="text-secondary">Statistics</h2>
        <table class="table">
            <thead>
                <tr>
                    <td scope="col"></td>
                    <td scope="col">Structure</td>
                    <td scope="col">Channel</td>
                    <td scope="col" class="text-right">Mean</td>
                    <td scope="col" class="text-right">Median</td>
                    <td scope="col" class="text-right">Standard Deviation</td>
                    <td scope="col" class="text-right">Skew</td>
                    <td scope="col" class="text-right">Kurtosis</td>
                </tr>
            </thead>
            <tbody>
                {% for item in key %}
                    <tr>
                        <td>
                            <div style="width: 50px; height: 10px; background-color: {{ key[item] }};">
                                &nbsp;
                            </div>
                        </td>
                        <td>{{ item[0] }}</td>
                        <td>{{ item[1] + (" - " + item[2] if item|length > 2 else "") }}</td>
                        <td class="text-right">{{ "%.8f"|format(mean[item]) }}</td>
                        <td class="text-right">{{ "%.8f"|format(median[item]) }}</td>
                        <td class="text-right">{{ "%.8f"|format(std[item]) }}</td>
                        <td class="text-right">{{ "%.8f"|format(skew[item]) }}</td>
                        <td class="text-right">{{ "%.8f"|format(kurtosis[item]) }}</td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    {% else %}
        <div class="alert alert-warning">
            Please select a date range and channel above then click generate
        </div>
    {% endif %}
</div>
{% endblock %}