<html>

<head>

    <title>TRIXI - {{ title }}</title>

    <link rel="stylesheet" type="text/css"
          href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css"/>
    <link rel="stylesheet" type="text/css"
          href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.bootstrap4.min.css"/>
    <link rel="stylesheet" type="text/css"
          href="https://cdn.datatables.net/select/1.2.5/css/select.bootstrap4.min.css"/>
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">


    <link href="https://fonts.googleapis.com/css?family=Roboto:300" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/custom.css') }}"/>

    <script type="text/javascript" charset="utf8"
            src="https://cdn.datatables.net/v/bs4-4.0.0/jq-3.2.1/dt-1.10.16/datatables.min.js"></script>

    <link rel="shortcut icon" type="image/png" href="{{ url_for('static', filename='assets/trixi-icon.png') }}"/>


</head>

<body>
<!-- <div class="container-fluid">
    <h1>{{ title }}</h1>
</div> -->
<div class="content">

    <table id="overviewTable" class="table table-bordered" cellspacing="0" width="100%">
        <thead>
        <tr>
            <th>Directory</th>
            <th class="center-elem">Name</th>
            <th class="center-elem">Time</th>
            <th class="center-elem">State</th>
            <th class="center-elem">Epochs</th>
            {% for c in ccols1 %}
            <th style="background-color: #dcedc8" class="center-elem">{{ c }}</th>
            {% endfor %}
            {% for c in ccols2 %}
            <th style="background-color: #dcedc8" class="center-elem">{{ c }}</th>
            {% endfor %}

            {% for c in rcols %}
            <th style="background-color: #fff3e0" class="center-elem">{{ c }}</th>
            {% endfor %}
        </tr>
        </thead>
        <tbody>
        {% for dir, star ,name, time, desc, epochs, config_vals, result_vals in rows %}
        <tr dir_name="{{ dir }}">
            <th>
                {% if star %}
                <a class="star_element" href="" style="color:black; margin-right: 0.5em;" dir_name="{{ dir }}"><i
                        class="material-icons"
                        style="vertical-align: middle;">star</i></a><a
                    href="/experiment?exp={{ dir }}" style="vertical-align: middle" target="_blank">{{ dir }}</a>
                {% else %}
                <a class="star_element" href="" style="color:black; margin-right: 0.5em;" dir_name="{{ dir }}"><i
                        class="material-icons"
                        style="vertical-align: middle;">star_border</i></a><a
                    href="/experiment?exp={{ dir }}" style="vertical-align: middle" target="_blank">{{ dir }}</a>
                {% endif %}
            </th>
            <td>
                <span>{{ name }}</span>
                <a class="edit_name" href="" style="color:black;" data-toggle="modal" data-target="#renameModal"
                   data-name="{{name}}" data-dir="{{dir}}">
                    <i class="material-icons" style="float: right;">edit</i>
                </a>
            </td>
            <td>{{ time }}</td>
            <td>{{ desc }}</td>
            <td>{{ epochs }}</td>
            {% for el, el_short in config_vals %}
            <td title="{{ el }}">{{ el_short }}</td>
            {% endfor %}
            {% for el, el_short in result_vals %}
            <td title="{{ el }}">{{ el_short }}</td>
            {% endfor %}
        </tr>
        {% endfor %}
        </tbody>
        <tfoot>
        <tr>
            <th>Dir</th>
            <th>Name</th>
            <th>Time</th>
            <th>State</th>
            <th>Epochs</th>
            {% for c in ccols1 %}
            <th>{{ c }}</th>
            {% endfor %}
            {% for c in ccols2 %}
            <th>{{ c }}</th>
            {% endfor %}
            {% for c in rcols %}
            <th>{{ c }}</th>
            {% endfor %}
        </tr>
        </tfoot>
    </table>
    <div class="container-fluid">
        <div class="row">
            <div class="col-auto" style="padding-right: 2px">
                <a role="button" class="btn btn-outline-secondary toggle-config">Toggle all</a><br><br>
            </div>
            <div class="col" style="padding-left: 2px">
                <div>
                    {% for c in ccols1 %}
                    <a role="button" class="btn btn-outline-success toggle-vis" data-column="{{ loop.index + 4 }}"
                       data-type="config">{{ c }}</a>
                    {% endfor %}
                </div>
                <div div class="collapse" id="collapseExample">
                    {% for c in ccols2 %}
                    <a role="button" class="btn btn-outline-success toggle-vis"
                       data-column="{{ loop.index + ccols1|length + 4 }}"
                       data-type="config">{{ c }}</a>
                    {% endfor %}
                </div>
            </div>
            <div class="col-auto" style="padding-left: 2px">
                <a role="button" class="btn btn-outline-secondary" data-toggle="collapse" href="#collapseExample">+/-
                </a>
            </div>
        </div>

        <div class="row" style="margin-top: 5px">
            <div class="col-auto" style="padding-right: 2px">
                <a role="button" class="btn btn-outline-secondary toggle-result">Toggle all</a>
            </div>
            <div class="col" style="padding-left: 2px">
                {% for c in rcols %}
                <a role="button" class="btn btn-outline-warning toggle-vis"
                   data-column="{{ loop.index + ccols1|length + ccols2|length + 4 }}"
                   data-type="result">{{ c }}</a>
                {% endfor %}
            </div>
        </div>
        <div class="row" style="margin-top: 5px">
            <div class="col-auto">
                <button type="button" class="btn btn-outline-secondary" data-toggle="modal" data-target="#switchModal">
                    Switch to...
                </button>
            </div>
        </div>
    </div>


</div>

<!-- Modal -->
<div class="modal fade" id="switchModal" tabindex="-1" role="dialog" aria-labelledby="switchModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="switchModalLabel">Switch to another directory</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <a href="/">HOME</a>
                <hr>
                {% for e in noexp %}
                <a href="/overview?dir={{ e }}">{{ e }}</a><br>
                {% endfor %}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<div class="text-center" style="margin: 2em">
    <img src="{{ url_for('static', filename='assets/trixi-small.png') }}" width="50px"/>
</div>


<!-- Modal -->
<div class="modal fade" id="renameModal" tabindex="-1" role="dialog" aria-labelledby="renameModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="renameModalLabel">Change Name</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <label class="col-form-label">Name:</label>
                <input type="text" class="form-control" id="experiment-rename-input">
            </div>
            <div class="modal-footer">
                <a type="button" class="btn btn-secondary" data-dismiss="modal">Close</a>
                <a type="button" class="btn btn-primary" id="rename-modal-button" data-dismiss="modal">Change Name</a>
            </div>
        </div>
    </div>
</div>


<!-- Modal -->
<div class="modal fade" id="combineModal" tabindex="-1" role="dialog" aria-labelledby="renameModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="combineModalLabel">Combine Experiments</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <label class="col-form-label">Name:</label>
                <input type="text" class="form-control" id="combi-name-input">
                <br>
                 <div style="float: right;">
                    <label class="switch">
                        <input type="checkbox"  id="combi-save-input" checked>
                        <span class="slider round"></span>
                    </label>
                    <div>Save</div>
                </div>


            </div>
            <div class="modal-footer">
                <a type="button" class="btn btn-secondary" data-dismiss="modal">Close</a>
                <a type="button" class="btn btn-primary" id="combi-modal-button" data-dismiss="modal">Combine</a>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="combineModal2" tabindex="-1" role="dialog" aria-labelledby="renameModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="combineModalLabel2">Combine All Experiments</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <label class="col-form-label">Name:</label>
                <input type="text" class="form-control" id="combi-name-input2">
                <br>
                Group By:
                <div id="combi-checkboxlist">
                    {% for c in ccols1 %}
                    <div><input type="checkbox" value="{{ c }}" class="chk"> {{ c }}</div>
                    {% endfor %}

                </div>

            </div>
            <div class="modal-footer">
                <a type="button" class="btn btn-secondary" data-dismiss="modal">Close</a>
                <a type="button" class="btn btn-primary" id="combi-modal-button2" data-dismiss="modal">Combine&Save</a>
            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="LoadingModal" tabindex="-1" role="dialog" aria-labelledby="renameModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Loading...</h5>
                 <i class="fa fa-circle-o-notch fa-spin" style="font-size:24px"></i>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="ErrorModal" tabindex="-1" role="dialog" aria-labelledby="renameModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Error</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>An Error has occurred. Please reload.</p>
            </div>
            <div class="modal-footer">
                <a type="button" class="btn btn-secondary" data-dismiss="modal">Close</a>
            </div>
        </div>
    </div>
</div>

<script>

    var search_dict = {};
    var removed_list = [];
    var last_td;

    // Extended Search so you can search with <, <= , >, >=
    $.fn.dataTable.ext.search.push(
        function (settings, data, dataIndex) {

            var show_draw_row = true;

            if (removed_list.indexOf($.trim(data[0])) >= 0) {
                return false;
            }

            for (var key in search_dict) {
                if (search_dict.hasOwnProperty(key)) {
                    var val = search_dict[key];
                    var data_el = data[key];

                    if (data_el === "-") {
                        show_draw_row = false;
                    }
                    else if (val.startsWith(">=")) {
                        var numb = parseFloat(val.substring(2));
                        if (data_el < numb) {
                            show_draw_row = false;
                        }
                    }
                    else if (val.startsWith(">")) {
                        var numb = parseFloat(val.substring(1));
                        if (data_el <= numb) {
                            show_draw_row = false;
                        }
                    }
                    else if (val.startsWith("<=")) {
                        var numb = parseFloat(val.substring(2));
                        if (data_el > numb) {
                            show_draw_row = false;
                        }
                    }
                    else if (val.startsWith("<")) {
                        var numb = parseFloat(val.substring(1));
                        if (data_el >= numb) {
                            show_draw_row = false;
                        }
                    }
                }
            }
            return show_draw_row;
        }
    );

    $(document).ready(function () {

        // Setup - add a text input to each footer cell
        $('#overviewTable tfoot th').each(function () {
            var title = $(this).text();
            $(this).html('<input type="text" placeholder="Search ' + title + '" />');
        });

        // Selectable rows
        $('#overviewTable tbody').on('click', 'tr', function (e) {
            // e.preventDefault();
            $(this).toggleClass('selected');
        });

        // DataTable
        var table = $('#overviewTable').DataTable({
            scrollY: '70vh',
            scrollCollapse: true,
            paging: false,
            scrollX: true,
            select: {
                items: 'rows'
            },
            info: "",
            dom: 'l<"toolbar">frtip',
            initComplete: function () {
                $("div.toolbar")
                    .html('<a role="button" class="compare-experiments btn btn-primary" style="float: left">Details</a>\
                           <a role="button" class="combine-experiments btn btn-success" style="float: left;margin-left:                                                       2px;">Combine</a>\
                           <a role="button" class="remove-experiments btn btn-danger" style="float: left; margin-left: 2px;">Remove</a>');
            },
            columnDefs: [
                {targets: [0, 1, 2, 3, 4], visible: true},
                {targets: "_all", visible: false}
            ],
            aaSorting: [[2, 'desc']]
        });

        // Compare experiments
        $('a.compare-experiments').on('click', function (e) {
            e.preventDefault();
            var experiments = [];
            $.each($('#overviewTable tr.selected'), function () {
                var dir_name = $(this)[0].getAttribute("dir_name");
                experiments.push(dir_name);
            });
            if (experiments.length > 0) {
                var new_location = "experiment?";
                $.each(experiments, function (idx, val) {
                    new_location = new_location + "exp=" + val + "&";
                });
                // window.location.href = new_location;
                window.open(new_location, '_blank');
            }
        });

        $('a.remove-experiments').on('click', function (e) {
            e.preventDefault();
            var experiments = {};
            $.each($('#overviewTable tr.selected'), function () {
                var dir_name = $(this)[0].getAttribute("dir_name");
                experiments[dir_name] = $.trim($(this).find('th').eq(0).text());
            });
            if (Object.keys(experiments).length > 0) {
                var url_exp_remove = "experiment_remove?";
                $.each(experiments, function (key, val) {
                    url_exp_remove = url_exp_remove + "exp=" + key + "&";
                    removed_list.push(val);
                });

                $.get(
                    url_exp_remove,
                    {},
                    function (data) {
                        $.each(experiments, function (key, val) {
                            removed_list.push(val);
                        });
                    }
                );
                table.draw();

            }
        });

        $('a.combine-experiments').on('click', function (e) {
            e.preventDefault();
            var experiments = [];
            $.each($('#overviewTable tr.selected'), function () {
                var dir_name = $(this)[0].getAttribute("dir_name");
                experiments.push(dir_name);
            });
            if (experiments.length > 1) {
                $('#combineModal').modal({show: true});
            }
            else if(experiments.length < 1){
                $('#combineModal2').modal({show: true});
            }
        });

        $('a.star_element').on('click', function (e) {
            e.preventDefault();

            var dir_name = $(this)[0].getAttribute("dir_name");
            var url_exp_star = "experiment_star?" + "exp=" + dir_name;
            var text = $(this)[0].text;
            var th = $(this);
            if (text === "star_border") {
                url_exp_star = url_exp_star + "&star=" + 1;
                $.get(
                    url_exp_star,
                    {},
                    function () {

                        th[0].innerHTML = '<i class="material-icons"\n' +
                            '                                   style="vertical-align: middle">star</i>';
                    }
                );
            }
            else if (text === "star") {
                url_exp_star = url_exp_star + "&star=" + 0;
                $.get(
                    url_exp_star,
                    {},
                    function () {
                        th[0].innerHTML = '<i class="material-icons"\n' +
                            '                                   style="vertical-align: middle">star_border</i>';
                    }
                );
            }

        });


        $('a.edit_name').on('click', function (e) {
            e.preventDefault();
            last_td = $(this)[0].parentElement.children[0];
        });

        $('#renameModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget); // Button that triggered the modal
            var name = button.data('name'); // Extract info from data-* attributes
            var dir = button.data('dir');

            var modal = $(this);
            modal.find('#rename-modal-button')[0].setAttribute("exp-dir", dir);
            modal.find('.modal-body input').val(name);
        });

        $('#rename-modal-button').on('click', function (e) {
            e.preventDefault();
            var name_input = document.getElementById('experiment-rename-input');
            var new_name = name_input.value;
            var exp_dir = $(this)[0].getAttribute("exp-dir");

            var rename_url = "experiment_rename?exp=" + exp_dir + "&name=" + new_name;

            $.get(
                rename_url,
                {},
                function () {
                    last_td.innerHTML = new_name;
                }
            );


        });

        $('#combi-modal-button').on('click', function (e) {
            e.preventDefault();
            var name_input = document.getElementById('combi-name-input');
            var new_name = name_input.value;

            var save_input = document.getElementById('combi-save-input');
            var do_save = save_input.checked;

            var experiments = [];
            $.each($('#overviewTable tr.selected'), function () {
                var dir_name = $(this)[0].getAttribute("dir_name");
                experiments.push(dir_name);
            });
            if (experiments.length > 0) {
                var new_location = "experiment?";
                $.each(experiments, function (idx, val) {
                    new_location = new_location + "exp=" + val + "&";
                });
                new_location += "name=" + new_name + "&";
                new_location += "save=" + do_save+ "&";
                new_location += "combi=true";
                // window.location.href = new_location;

                window.open(new_location, '_blank');
            }

        });

         $('#combi-modal-button2').on('click', function (e) {
            e.preventDefault();
            var name_input = document.getElementById('combi-name-input2');
            var new_name = name_input.value;

            var experiments = [];
            $.each($('#overviewTable tr'), function () {
                var dir_name = $(this)[0].getAttribute("dir_name");
                if(dir_name != null) {
                    experiments.push(dir_name);
                }
            });

            var chkArray = [];
            $(".chk:checked").each(function() {
                chkArray.push($(this).val());
            });

            var new_location = "combine?";
            $.each(experiments, function (idx, val) {
                new_location = new_location + "exp=" + val + "&";
            });
            $.each(chkArray, function (idx, val) {
                new_location = new_location + "group=" + val + "&";
            });
            new_location += "name=" + new_name + "&";

            $.get(
                new_location,
                {},
                function (data) {
                    console.log("Combined Experiments");
                    $('#LoadingModal').modal().hide();
                    if (data === "1") {
                        location.reload();
                    }
                    else{
                        $('#ErrorModal').modal({show: true});
                    }
                }
            );
            $('#LoadingModal').modal({show: true});



        });

        function toggle(button, redraw=true) {
            // Get the column API object
            var column = table.column(button.attr('data-column'));
            // Toggle the visibility
            column.visible(!column.visible(), redraw);

            if (button.attr('data-type') == "config") {
                if (column.visible()) {
                    button.removeClass("btn-outline-success");
                    button.addClass("btn-success");
                } else {
                    button.removeClass("btn-success");
                    button.addClass("btn-outline-success");
                }
            }
            if (button.attr('data-type') == "result") {
                if (column.visible()) {
                    button.removeClass("btn-outline-warning");
                    button.addClass("btn-warning");
                } else {
                    button.removeClass("btn-warning");
                    button.addClass("btn-outline-warning");
                }
            }
        };

        $('a.toggle-vis').on('click', function (e) {
            e.preventDefault();
            toggle($(this));
        });

        $('a.toggle-config').on('click', function (e) {
            e.preventDefault();
            var configbuttons = $('a[data-type="config"]');
            var n = configbuttons.length;
            configbuttons.each(function (i, obj) {
                if (i != n - 1) {
                    toggle($(obj), false);
                } else {
                    toggle($(obj));
                }
            });
        });

        $('a.toggle-result').on('click', function (e) {
            e.preventDefault();
            var resultbuttons = $('a[data-type="result"]');
            var n = resultbuttons.length;
            resultbuttons.each(function (i, obj) {
                if (i != n - 1) {
                    toggle($(obj), false);
                } else {
                    toggle($(obj));
                }
            });
        });

        // Apply the search
        table.columns().every(function () {
            var that = this;
            $('input', this.footer()).on('keyup change', function () {

                var cidx = that[0];
                var pre_str = this.value.replace(/\s/g, "");

                if (pre_str.startsWith(">") || pre_str.startsWith("<")) {
                    search_dict[cidx] = pre_str;
                    table.draw();

                }
                else {
                    if (!pre_str || 0 === pre_str.length) {
                        delete search_dict[cidx];
                        table.draw();
                    }
                    if (that.search() !== this.value) {
                        that
                            .search(this.value)
                            .draw();
                    }
                }
            });
        });

    });
</script>
</body>

</html>
