{% extends 'base.html' %}
{% block title %}IvoryOS | Design execution{% endblock %}

{% block body %}
    <div id="overlay" class="overlay">Please wait...</div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.js"></script>


    {% if no_deck_warning and not dismiss %}
{#      auto pop import when there is no deck#}
        <script type="text/javascript">
            function OpenBootstrapPopup() {
                $("#importModal").modal('show');
            }
            window.onload = function () {
                OpenBootstrapPopup();
            };
        </script>
    {% endif %}

    <div class="accordion" id="accordionPanelsStayOpenExample">
        <div class="accordion-item design-control">
            <h2 class="accordion-header">
                <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#runpanel" aria-expanded="true" aria-controls="runpanel">
                    Run Panel
                </button>
            </h2>
            <div id="runpanel" class="accordion-collapse collapse show">
                <div class="accordion-body">
                    {% if script['script'] or script['prep'] or script['cleanup'] %}
                        <div class="row">
                            <div class="col-lg-6 col-sm-12">
                                <ul class="nav nav-tabs" id="myTabs" role="tablist">
                                    <li class="nav-item" role="presentation">
                                        <a class="nav-link {{ 'disabled' if config_list else '' }} {{ 'active' if not config_list else '' }}" id="tab1-tab" data-bs-toggle="tab" href="#tab1" role="tab" aria-controls="tab1" aria-selected="false">Simple repeat</a>
                                    </li>
                                    <li class="nav-item" role="presentation">
                                        <a class="nav-link {{ 'disabled' if (not config_list or config_list|count > 5) else '' }} {{ 'active' if config_list and config_list|count < 6 else '' }}" id="tab4-tab" data-bs-toggle="tab" href="#tab4" role="tab" aria-controls="tab4" aria-selected="false">Quick config</a>
                                    </li>
                                    <li class="nav-item" role="presentation">
                                        <a class="nav-link {{ 'disabled' if not config_list else '' }} {{ 'active' if config_list|count > 5 else '' }}" id="tab2-tab" data-bs-toggle="tab" href="#tab2" role="tab" aria-controls="tab2" aria-selected="false">Excel configuration</a>
                                    </li>

                                    <li class="nav-item" role="presentation">
                                        <a class="nav-link {{ 'disabled' if not config_list or not return_list else '' }}" id="tab3-tab" data-bs-toggle="tab" href="#tab3" role="tab" aria-controls="tab3" aria-selected="false">Bayesian Optimization</a>
                                    </li>
                                </ul>
                                <div class="tab-content" id="myTabsContent">
                                    <div class="tab-pane fade {{ 'show active' if not config_list else '' }}" id="tab1" role="tabpanel" aria-labelledby="tab1-tab">
                                        <p><h5>Control panel:</h5></p>
                                        <form role="form" method='POST' name="run" action="{{url_for('design.experiment_run')}}">
                                            <div class="input-group mb-3">
                                                <label class="input-group-text" for="repeat">Repeat for </label>
                                                <input class="form-control" type="number" id="repeat" name="repeat" min="1" max="100">
                                                <label class="input-group-text" for="repeat"> times</label>
                                            </div>
{#                                            {% if not no_deck_warning%}#}
                                                <div class="input-group mb-3">
                                                    <button class="form-control" type="submit" class="btn btn-dark">Run</button>
                                                </div>
{#                                            {% endif %}#}
                                        </form>
                                    </div>
                                    <div class="tab-pane fade {{ 'show active' if config_list|count>5 else '' }}" id="tab2" role="tabpanel" aria-labelledby="tab2-tab">

                                        <p><h5>Control with csv config:</h5></p>
                                        <p>Current configure: {{ filename }}</p>
                                        <div>
                                            
                                            <form method="GET" action="{{ url_for("design.experiment_run") }}" enctype="multipart/form-data">
                                                <div class="input-group mb-3">
                                                    <select class="form-select" name="filename" id="filename" required onchange="document.getElementById('filename').submit();">
                                                        <option selected disabled hidden style="overflow-wrap: break-word;" name="filename" id="filename" value=""> -- choose config file --</option>
                                                        {% for config_file in config_file_list %}
                                                            <option {{'selected' if filename==config_file else '' }} style="overflow-wrap: break-word;" name="filename" id="filename" value="{{config_file}}">{{config_file}}</option>
                                                        {% endfor %}
                                                    </select>
{#                                                    <button type="submit"  class="btn btn-primary"> Change config file </button>#}
                                                </div>
                                            </form>

{#                                                    <li><a class="dropdown-item" data-bs-toggle="collapse" href="#preview" role="button" aria-expanded="false">Preview config</a></li>#}
                                            <a class="btn btn-primary" href="{{ url_for('design.download', filetype='configure') }}" >empty config</a>
                                            <a class="btn btn-primary" data-bs-toggle="collapse" href="#loadfile" role="button" aria-expanded="false">Upload .csv</a>

                                        
                                            <div class="collapse" id="loadfile">
                                                <form method="POST" action="{{ url_for('design.upload') }}" enctype="multipart/form-data">
                                                    <div class="input-group">
                                                        <input class="form-control" name="file" type="file" required="required" onchange="document.getElementById('file').submit();">
                                                        <input class="btn btn-secondary" type="submit" value="Upload .csv">
                                                    </div>
                                                </form>
                                            </div>
                                        </div>

                                        {#Preview config file#}
                                        <div id="preview">
                                        {% if config_preview %}
                                            <table class="table table-hover">
                                                <thead>
                                                <tr>
                                                    {% for line in config_preview[0].keys() %}
                                                        <th scope="col">{{ line }}</th>
                                                    {% endfor %}
                                                </tr>
                                                </thead>
                                                <tbody>
                                                {% for line in config_preview %}
                                                    <tr>
                                                        {% for i in line.values() %}
                                                            <td>{{ i }}</td>
                                                        {% endfor %}
                                                    </tr>
                                                {% endfor %}
                                                </tbody>
                                            </table>
                                        {% else %}
                                            Empty config file
                                        {% endif %}
                                        </div>
                                        {% if filename and not no_deck_warning %}
                                            <form role="form" method='POST' name="run" action="{{ url_for('design.experiment_run')}}">
                                                <div class="form-group">
                                                    <button type="submit" class="btn btn-success">Run</button>
                                                </div>
                                            </form>
                                        {% endif %}
                                    </div>
                                
                                    <div class="tab-pane fade " id="tab3" role="tabpanel" aria-labelledby="tab3-tab">
                                        <form role="form" method='POST' name="bo" action="{{ url_for('design.experiment_run')}}">
                                            <div class="form-group">
                                                <p><h5>Parameters:</h5><p>
                                                {% for config in config_list %}
                                                    <div class="row g-3 align-items-center">
                                                        <div class="col-lg-3 col-sm-6 ">
                                                            {{config}}:
                                                        </div>
{#                                                        <div class="col-auto">#}
{#                                                            <label class="col-form-label" for="{{config}}_type">Type</label>#}
{#                                                        </div>#}
                                                        <div class="col-auto">
                                                            <select class="form-select" id="{{config}}_type" name="{{config}}_type">
                                                                <option selected value="range">range</option>
                                                                <option value="choice">choice</option>
                                                                <option value="fixed">fixed</option>
                                                            </select>
                                                        </div>
                                                        <div class="col-auto">
                                                            <label class="" for="{{config}}_value">Values</label>
                                                        </div>
                                                        <div class="col-auto">
                                                            <input type="text" class="form-control" id="{{config}}_value" name="{{config}}_value" placeholder="1, 2, 3">
                                                        </div>
{#                                                        <div class="col-auto">#}
{#                                                            <input type="text" class="form-control" id="{{config}}_value_max" style="display: none;" placeholder="1, 2, 3">#}
{#                                                        </div>#}
                                                    </div>
                                                {% endfor %}
                                                <p><h5>Objective:</h5><p>
                                                {% for objective in return_list %}
                                                    <div class="row gy-2 gx-3 align-items-center input-group">
                                                        <div class="col-3">
                                                            {{objective}}:
                                                        </div>
{#                                                        <div class="col-auto">#}
{#                                                            <label class="" for="{{objective}}_min">Minimize</label>#}
{#                                                        </div>#}
                                                        <div class="col-auto">
                                                            <select class="form-select" id="{{objective}}_min" name="{{objective}}_min">
                                                                <option selected>minimize</option>
                                                                <option>maximize</option>
                                                                <option>none</option>
                                                            </select>
                                                        </div>
{#                                                        <div class="col-auto">#}
{#                                                            <label class=""  for="{{objective}}_threshold">Threshold</label>#}
{#                                                        </div>#}
{#                                                        <div class="col-auto">#}
{#                                                            <input type="text" class="form-control" id="{{objective}}_threshold" name="{{objective}}_threshold" placeholder="None">#}
{#                                                        </div>#}
                                                    </div>
                                                {% endfor %}
                                                <p><h5>Budget:</h5></p>
                                                <div class="input-group mb-3">
                                                    <label class="input-group-text" for="repeat">Max iteration </label>
                                                    <input class="form-control" type="number" id="repeat" name="repeat" min="1" max="100">
                                                </div>
                                                {% if not no_deck_warning%}
                                                    <div class="input-group mb-3">
                                                        <button class="form-control" type="submit" name="bo">Run</button>
                                                    </div>
                                                {% endif %}
                                            </div>
                                        </form>
                                    </div>
                                    <div class="tab-pane fade {{ 'show active' if config_list and config_list|count<=5 else '' }}" id="tab4" role="tabpanel" aria-labelledby="tab4-tab">
                                        <p><h5>Control panel:</h5></p>
                                        <div>
                                            <form method="POST" name="online-config" id="online-config" action="{{url_for('design.experiment_run')}}">
                                                <table id="dataInputTable" class="table table-striped">
                                                    <thead class="thead-dark">
                                                    <tr>
                                                        {% for column in config_list %}
                                                            <th>{{ column }}</th>
                                                        {% endfor %}
                                                    </tr>
                                                    </thead>
                                                    <tbody>
                                                    </tbody>
                                                </table>
                                                <div class="btn btn-light" onclick="addRow()"><i class="bi bi-plus-circle" ></i></div>
                                                <button type="submit" name="online-config" class="btn btn-success">Run</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-6 col-sm-12 logging-panel">
                                <p>
                                <div class="p d-flex justify-content-between align-items-center">
                                    <h5>Progress：</h5>
                                    <button id="abort" class="btn btn-danger ">Abort Pending Actions</button>
                                </div>
                                </p>
                                <div class="progress" role="progressbar" aria-label="Animated striped example" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100">
                                    <div id="progress-bar-inner" class="progress-bar progress-bar-striped progress-bar-animated"></div>
                                </div>
                                <p><h5>Log：</h5></p>
                                <div id="logging-panel"></div>
                            </div>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
        <div class="accordion-item design-control">
            <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#data" aria-expanded="false" aria-controls="script">
                    Download experiment data csv
                </button>
            </h2>
            <div id="data" class="accordion-collapse collapse">
                <div class="accordion-body">
                    {% if session["most_recent_result"] %}
                        <p><a href="{{ url_for('design.download_results', filename=session["most_recent_result"]) }}">Download the latest data <i class="bi bi-download"></i></a></p>
                    {% endif %}
                    <p>
                    <h5>All data files</h5>
                    {% for datafile in data_list %}
                        <div>
                            {{ datafile }} <a href="{{ url_for('design.download_results', filename=datafile) }} "><i class="bi bi-download"></i></a>
                        </div>
                    {% endfor %}
                    </p>
                </div>
            </div>
        </div>
        <div class="accordion-item design-control">
            <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#script" aria-expanded="false" aria-controls="script">
                    Script
                </button>
            </h2>
            <div id="script" class="accordion-collapse collapse">
                <div class="accordion-body">
                    {% for script_type in ['prep', 'script', 'cleanup'] %}
                        {% if script[script_type] %}
                            <h6>
                                {% if script_type == 'prep' %} Preparation: {% elif script_type == 'script' %} Experiment:
                                {% elif script_type == 'cleanup' %} Clean up: {% endif %}
                            </h6>
                            <ul>
                                {% for s in script[script_type] %}{% if not s['instrument']=='if' and not s['instrument']=='while' %} &emsp; {% endif %}
                                    <li class="btn btn-light" id="{{s['id']}}" style="{{'background-color: tomato' if s['instrument']=='if' else 'background-color: darkcyan' if s['instrument']=='while' else ''}}">
                                        {% if s['return'] %}{{ s['return'] }} = {% endif %}
                                        {{ s['action'] }}
{#                                           {% if s['action']== 'if' %} {% if s['args'] %}({{ s['args'] }}) {% else %} True {% endif %}#}
{#                                           {% elif s['action']== 'while' %} {% if s['args'] %}({{ s['args'] }}) {% else %} False {% endif %}#}
                                        {% if s['instrument']== 'variable' %} = {{ s['args'] }}
                                        {% else %} {% if s['args'] %} ({{ s['args'] }}) {% endif %}
                                        {% endif %}
                                    </li>
                                    <div class="clear"></div>
                                {% endfor %}
                            </ul>
                        {% endif %}
                    {% endfor %}
                </div>
            </div>
        </div>
        <div class="accordion-item design-control">
            <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#python" aria-expanded="false" aria-controls="python">
                    Python Script
                </button>
            </h2>
            <div id="python" class="accordion-collapse collapse">
                <div class="accordion-body">
                    <pre><code class="python" >{{dot_py}}</code></pre>
                    <a href="{{ url_for('design.download', filetype='python') }}">Download <i class="bi bi-download"></i></a>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.getElementById('{{config}}_type').addEventListener('change', function() {
            const extraInputBox = document.getElementById('{{config}}_value_max');

            if (this.value === 'range') {
                extraInputBox.style.display = 'block';
            } else {
                extraInputBox.style.display = 'none';
            }
        });
    </script>
    <script>
        {# // Initially add 5 rows when the page loads #}
        document.addEventListener("DOMContentLoaded", function() {
            for (let i = 0; i < 5; i++) {
                addRow();
            }
        });
    </script>
    <script>
        {#var socket = io.connect('http://' + document.domain + ':' + location.port);#}
        var socket = io()
        socket.on('connect', function() {
            console.log('Connected');
        });
        socket.on('progress', function(data) {
            var progress = data.progress;
            console.log(progress);
            $('#progress-bar-inner').css('width', progress + '%')
        });
        socket.on('log', function(data) {
            var logMessage = data.message;
            console.log(logMessage);
            $('#logging-panel').append(logMessage+"<br>");
            $('#logging-panel').scrollTop($('#logging-panel')[0].scrollHeight);
        });
        document.getElementById('abort').addEventListener('click', function() {
            var confirmation = confirm("Are you sure you want to abort pending actions?");
            if (confirmation) {
                socket.emit('abort_action');
                console.log('Abort action sent to server.');
            }
        });
    </script>
    <script>
        var rowCount = 0; // Initialize row count
        function addRow() {
            rowCount++; // Increment row count each time a row is added
            var table = document.getElementById("dataInputTable");
            var newRow = table.insertRow(-1); // Adds a row at the end of the table
            {% for column, type in config_type_list.items()  %}
            var cell = newRow.insertCell(-1);
            cell.innerHTML = '<input type="text" class="form-control" name="{{ column }}[' + rowCount + ']" placeholder={{ type }}>';
            {% endfor %}
        }
    </script>

{% endblock %}
