{% import 'macros_profile_overview.html.jinja2' as profile_overview %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
    {%- if not offline %}
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.css">
    <script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.js"></script>
    {%- endif %}
    <style>
        html {
             font-family: "Courier New", Courier, monospace;
        }
        .column {
            width: 48%;
            margin: 0 1%;
        }
        .left {
            float: left;
        }
        .right {
            float: right;
        }
        .column-head {
            border-bottom: 1px solid #ddd;
            border-top: 1px solid #ddd;
            text-align: center;
        }
        .aboveThreshold {
            font-weight: bold;
            color: #902000;
            background-color: salmon !important;
        }
        .clear {
            clear: both;
        }
        td.details-control {
            text-align: center;
            cursor: pointer;
        }
        tr.shown td.details-control {
            text-align: center;
        }
        tr.shown span.minus {
            display: block;
        }
        tr.shown span.plus {
            display: none;
        }
        tr.hidden span.plus {
            display: block;
        }
        tr.hidden span.minus {
            display: none;
        }

        div.tools table {
            border-collapse: collapse;
            border-bottom: 1px solid #ddd;
            border-top: 1px solid #ddd;
            margin: 0 auto 2em auto;
        }

        div.tools td.value {
            padding: 1em 0.5em;
            text-align: left;
        }

        div.tools td.key {
            padding: 1em 0.5em;
            text-align: right;
            font-weight: bold;
        }

        {{ profile_overview.css_style() }}
        {%- if offline %}
        {% include 'dataTables.dataTables.min.css' %}
        {%- endif %}
    </style>
</head>
<body>

<div class="left column">
    <h2 class="column-head">{{ lhs_tag }}</h2>
    {{ profile_overview.overview_table('toggleLeftCollapse', 'left-info', lhs_header, rhs_header, "Profile Specification") }}
    <div style="margin: 0 10px;">&nbsp;</div>
</div>


<div class="right column">
    <h2 class="column-head">{{ rhs_tag }}</h2>
    {{ profile_overview.overview_table('toggleRightCollapse', 'right-info', rhs_header, lhs_header, "Profile Specification") }}
    <div style="margin: 0 10px;">&nbsp;</div>
</div>

<div class="tools">
    <table>
        <tbody>
            <tr>
                <td class="key" title="Displays resources for different type.">Resource Type:</td>
                <td class="value" title="Displays resources for different type.">
                    <select class="filter" id="type_selector">
                    {% for data_type in data_types %}
                        <option value="{{ data_type }}">{{ data_type }}</option>
                    {%- endfor %}
                    </select>
                </td>
                <td class="key" title="Displays resources for different clusters.">Cluster Type:</td>
                <td class="value" title="Displays resources for different clusters.">
                    <select class="filter" id="cluster_selector">
                            <option value="all">All</option>
                        {% for cluster in cluster_types%}
                            <option value="{{ cluster }}">{{ cluster }}</option>
                        {%- endfor %}
                    </select>
                </td>
            </tr>
        </tbody>
    </table>
    <table>
        <tbody>
            <tr>
                <td class="key" title="Allows searching across both tables.">Global Search:</td>
                <td class="value" title="Allows searching across both tables."><input type="text" class="filter" id="filter_uid"></td>
                <td class="key" title="Highlights values higher than given threshold (as float number).">Relative Threshold:</td>
                <td class="value" title="Highlights values higher than given threshold (as float number)."><input type="text" class="filter" id="filter_threshold"></td>
            </tr>
        </tbody>
    </table>
</div>

<div class="left column">
    <table id="table1" class="display" style="width: 100%;">
        <thead>
            <tr>
                <th></th>
                {% for (column, title) in lhs_columns %}
                    <th title="{{ title }}">{{ column }}</th>
                {%- endfor %}
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th></th>
                {% for _ in lhs_columns %}
                    <th></th>
                {%- endfor %}
            </tr>
            <tr>
                <th></th>
                {% for (column, title) in lhs_columns %}
                    <th title="{{ title }}">{{ column }}</th>
                {%- endfor %}
            </tr>
        </tfoot>
    </table>
</div>

<div class="right column">
    <table id="table2" class="display" style="width: 100%;">
        <thead>
        <tr>
            <th></th>
            {% for (column, title) in rhs_columns %}
                <th title="{{ title }}">{{ column }}</th>
            {%- endfor %}
        </tr>
        </thead>
        <tfoot>
            <tr>
                <th></th>
                {% for _ in rhs_columns %}
                    <th></th>
                {%- endfor %}
            </tr>
            <tr>
                <th></th>
                {% for (column, title) in rhs_columns %}
                    <th title="{{ title }}">{{ column }}</th>
                {%- endfor %}
            </tr>
        </tfoot>
    </table>
</div>

<script>
    {%- if offline %}
    {% include 'jquery-3.6.0.min.js' %}
    {% include 'dataTables.min.js' %}
    {%- endif %}
    {{ profile_overview.toggle_script('toggleLeftCollapse', 'left-info') }}
    {{ profile_overview.toggle_script('toggleRightCollapse', 'right-info') }}
    $(document).ready( function () {
        var lhs = $("#table1").DataTable({
            data: lhs_data.data,
            columns: [
                {
                    className: "details-control",
                    orderable: false,
                    data: null,
                    defaultContent: "",
                    render: function () {
                        return '<span class="plus">[+]</span><span class="minus">[-]</span>';
                    },
                    width: "15px"
                },
                { data: "uid" },
                {
                    data: "abs",
                    className: "dt-body-right",
                    render: function (data, type) {
                        if (type === 'display') {
                            const floatValue = parseFloat(data);
                            const intValue = parseInt(data);
                            if (!isNaN(intValue) && intValue.toString() === data) {
                                var formatted_int= intValue.toLocaleString();
                                return `${formatted_int}`;
                            } else if(!isNaN(floatValue) && floatValue.toString() === data) {
                                var formatted_float = floatValue.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
                                return `${formatted_float}`;
                            } else {
                                return data;
                            }
                        }

                        return data;
                    },
                },
                { data: "rel" },
                { data: "type", visible: false},
                { data: "cluster", visible: false}
            ],
            createdRow: function( row, data, dataIndex ) {
                $( row ).addClass('hidden');
            },
            order: [[3, "desc"]],
            iDisplayLength: 50,
            columnDefs: [
                {
                    "targets": "_all",
                    "render": function(data, type, row, meta) {
                        if (type !== "display") {
                            return data;
                        }
                        return '<span title="' + row.cluster + '">' + data + '</span';
                    }
                }
            ],
            footerCallback: function (row, data, start, end, display) {
                let api = this.api();

                // Remove the formatting to get integer data for summation
                let intVal = function (i) {
                    const floatValue = parseFloat(i);
                    const intValue = parseInt(i);
                    const isFloatStr = typeof i === 'string' && (i.includes('.') || i.includes(','));
                    if (!isNaN(floatValue) && isFloatStr) {
                        return floatValue;
                    } else if(!isNaN(intValue)) {
                        return intValue;
                    } else {
                        return 0;
                    }
                };

                // Total over all pages
                total = api
                    .column(2, {page: 'current'})
                    .data()
                    .reduce((a, b) => intVal(a) + intVal(b), 0);

                // Update footer
                api.column(2).footer().innerHTML = total.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
            }
        });
        var rhs  = $("#table2").DataTable({
            data: rhs_data.data,
            columns: [
                {
                    className: "details-control",
                    orderable: false,
                    data: null,
                    defaultContent: "",
                    render: function () {
                        return '<span class="plus">[+]</span><span class="minus">[-]</span>';
                    },
                    width: "15px"
                },
                { data: "uid" },
                {
                    data: "abs",
                    className: "dt-body-right",
                    render: function (data, type) {
                        if (type === 'display') {
                            const floatValue = parseFloat(data);
                            const intValue = parseInt(data);
                            if (!isNaN(intValue) && intValue.toString() === data) {
                                var formatted_int= intValue.toLocaleString();
                                return `${formatted_int}`;
                            } else if(!isNaN(floatValue) && floatValue.toString() === data) {
                                var formatted_float = floatValue.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
                                return `${formatted_float}`;
                            } else {
                                return data;
                            }
                        }

                        return data;
                    },
                },
                { data: "rel" },
                { data: "type", visible: false},
                { data: "cluster", visible: false}
            ],
            createdRow: function( row, data, dataIndex ) {
                $( row ).addClass('hidden');
            },
            order: [[3, "desc"]],
            iDisplayLength: 50,
            columnDefs: [
                {
                    "targets": "_all",
                    "render": function(data, type, row, meta) {
                        if (type !== "display") {
                            return data;
                        }
                        return '<span title="' + row.cluster + '">' + data + '</span';
                    }
                }
            ],
            footerCallback: function (row, data, start, end, display) {
                let api = this.api();

                // Remove the formatting to get integer data for summation
                let intVal = function (i) {
                    const floatValue = parseFloat(i);
                    const intValue = parseInt(i);
                    const isFloatStr = typeof i === 'string' && (i.includes('.') || i.includes(','));
                    if (!isNaN(floatValue) && isFloatStr) {
                        return floatValue;
                    } else if(!isNaN(intValue)) {
                        return intValue;
                    } else {
                        return 0;
                    }
                };

                // Total over all pages
                total = api
                    .column(2, {page: 'current'})
                    .data()
                    .reduce((a, b) => intVal(a) + intVal(b), 0);

                // Update footer
                api.column(2).footer().innerHTML = total.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
            }
        });

        $('#table1 tbody').on('click', 'td.details-control', function() {
            var tr = $(this).closest('tr');
            var row = lhs.row(tr);

            if (row.child.isShown()) {
                row.child.hide();
                tr.removeClass('shown');
                tr.addClass('hidden');
            } else {
                row.child(format(row.data())).show();
                tr.removeClass('hidden');
                tr.addClass('shown');
            }
        });

        $('#table2 tbody').on('click', 'td.details-control', function() {
            var tr = $(this).closest('tr');
            var row = rhs.row(tr);

            if (row.child.isShown()) {
                row.child.hide();
                tr.removeClass('shown');
                tr.addClass('hidden');
            } else {
                row.child(format(row.data())).show();
                tr.removeClass('hidden');
                tr.addClass('shown');
            }
        });

        document.querySelectorAll('select.filter').forEach((el) => {
            el.addEventListener('change', () => {
                filterByType(lhs);
                filterByType(rhs);
                filterByClusters(lhs);
                filterByClusters(rhs);
            })
        });

        document.querySelectorAll('input.filter').forEach((el) => {
            el.addEventListener(el.type === 'text' ? 'keyup' : 'change', () => {
                filterGlobal(lhs);
                filterGlobal(rhs);
                highlightGlobal(lhs);
                highlightGlobal(rhs);
                updateSelect();
            })
        });

        filterByType(lhs);
        filterByType(rhs);
    });

    function format(d) {
        let result = '<table style="width: 100%;">';
        d.trace.forEach((value, index) => {
          result += "<tr>";
          result += '<td style="white-space: pre-wrap">' + value + "</td>";
          result += "</tr>";
        });
        result += '</table>';
        return result
    }

    function filterGlobal(table) {
        let filter = document.querySelector("#filter_uid");

        table.search(filter.value).draw();
    }

    function filterByType(table) {
        let selector = document.querySelector("#type_selector");

        table.columns(4).search(selector.value, {exact: true}).draw();
    }

    function filterByClusters(table) {
        let selector = document.querySelector("#cluster_selector");

        table.columns(5).search(selector.value, {exact: true}).draw();
    }

    function highlightGlobal(table) {
        const inputValue = parseFloat(document.querySelector("#filter_threshold").value)
        table.rows({search: 'applied', filter: 'applied'}).every(function () {
            const rowData = this.data();
            const columnValue = parseFloat(rowData['rel'].replace("%", ""));

            if (columnValue >= inputValue) {
                console.log("Above Threshold")
                $(this.node()).addClass("aboveThreshold");
            } else {
                $(this.node()).removeClass("aboveThreshold");
            }
        })
    }

    function updateSelect() {
        var uniqueValues = [];
        $('#table1').DataTable().rows().every(function() {
           var data = this.data();
           var value = data[5];
           if (!uniqueValues.includes(value)) {
               uniqueValues.push(value);
           }
        });

        $('#table2').DataTable().rows().every(function() {
            var data = this.data();
            var value = data[5];
            if (!uniqueValues.includes(value)) {
                uniqueValues.push(value);
            }
        });

        uniqueValues.sort();

        var select = document.getElementById("cluster_selector");
        select.innerHTML = '';
        uniqueValues.forEach(function(value) {
            var option = document.createElement('option');
            option.text = value;
            option.value = value;
            select.add(option);
        })

        var option = document.createElement('option');
        option.text = "All";
        option.value = "all";
        select.add(option);
    }

    const lhs_data = {
        "data": [
            {% for val in lhs_data %}
            {
                "uid": "{{ val.uid }}",
                "abs": "{{ val.abs_amount }}",
                "rel": "{{ val.rel_amount }}%",
                "trace": {{ val.trace_list }},
                "cluster": "{{ val.cluster.id }}",
                "type": "{{ val.type }}"
            },
            {%- endfor %}
        ]
    };
    const rhs_data = {
        "data": [
            {% for val in rhs_data %}
                {
                    "uid": "{{ val.uid }}",
                    "abs": "{{ val.abs_amount }}",
                    "rel": "{{ val.rel_amount }}%",
                    "trace": {{ val.trace_list }},
                    "cluster": "{{ val.cluster.id }}",
                    "type": "{{ val.type }}"
                },
            {%- endfor %}
        ]
    };
</script>

</body>
</html>