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

{% block body %}
    <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" id="run-panel"  style="{{ 'display: none;'  if pause_status else '' }}">
                                <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">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 config</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="1000" value="1">
                                                <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">
                                        <div>

                                        </div>
                                        <p><h5>Control with csv config:</h5></p>
                                        <p>Current configure: {{ filename }}</p>
                                        <div>

                                            <form name="filenameForm" id="filenameForm" 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="filenameSelect" required onchange="document.getElementById('filenameForm').submit();">
                                                        <option selected disabled hidden style="overflow-wrap: break-word;" value=""> -- choose config file --</option>
                                                        {% for config_file in config_file_list %}
                                                            <option {{'selected' if filename == config_file else '' }} style="overflow-wrap: break-word;" value="{{config_file}}">{{config_file}}</option>
                                                        {% endfor %}
                                                    </select>
                                                </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" name="loadfile">
                                                <form method="POST"  id="loadFile" name="loadFile" 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('loadFile').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="1000" value="25">#}
{#                                                </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" id="tab3" role="tabpanel" aria-labelledby="tab3-tab">
    <form method="POST" name="bo" action="{{ url_for('design.experiment_run') }}">
        <div class="container py-2">

            <!-- Parameters -->
            <h6 class="fw-bold mt-2 mb-1">Parameters</h6>
            {% for config in config_list %}
            <div class="row align-items-center mb-2">
                <div class="col-3 col-form-label-sm">
                    {{ config }}:
                </div>
                <div class="col-6">
                    <select class="form-select form-select-sm" 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-3">
                    <input type="text" class="form-control form-control-sm" id="{{config}}_value" name="{{config}}_value" placeholder="1, 2, 3">
                </div>
            </div>
            {% endfor %}

            <!-- Objective -->
            <h6 class="fw-bold mt-3 mb-1">Objectives</h6>
            {% for objective in return_list %}
            <div class="row align-items-center mb-2">
                <div class="col-3 col-form-label-sm">
                    {{ objective }}:
                </div>
                <div class="col-6">
                    <select class="form-select form-select-sm" id="{{objective}}_min" name="{{objective}}_min">
                        <option selected>minimize</option>
                        <option>maximize</option>
                        <option>none</option>
                    </select>
                </div>
            </div>
            {% endfor %}

            <h6 class="fw-bold mt-3 mb-1">Budget</h6>

            <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="1000" value="25">
            </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="d-flex align-items-center gap-2">
                                                    <div class="btn btn-light" onclick="addRow()">
                                                        <i class="bi bi-plus-circle"></i>
                                                    </div>
                                                    <button type="submit" name="online-config" class="form-control">Run</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-6 col-sm-12" id="code-panel" style="{{ '' if pause_status else 'display: none;'}}">
                                <p>
                                    <h5>Progress：</h5>
                                    {% if "prep" in line_collection.keys() %}                                        {% set stype = "cleanup" %}
                                        {% set stype = "prep" %}

                                        <h6>Preparation：</h6>
                                        {% for code in line_collection["prep"] %}
                                            <pre style="margin: 0; padding: 0; line-height: 1;"><code class="python" id="{{ stype }}-{{ loop.index0 }}" >{{code}}</code></pre>
                                        {% endfor %}
                                    {% endif %}
                                    {% if "script" in line_collection.keys() %}
                                        {% set stype = "script" %}

                                        <h6>Experiment：</h6>
                                        {% for code in line_collection["script"] %}
                                            <pre style="margin: 0; padding: 0; line-height: 1;"><code class="python" id="{{ stype }}-{{ loop.index0 }}" >{{code}}</code></pre>
                                        {% endfor %}
                                    {% endif %}
                                    {% if "cleanup" in line_collection.keys() %}
                                        {% set stype = "cleanup" %}
                                        <h6>Experiment：</h6>
                                        {% for code in line_collection["cleanup"] %}
                                            <pre style="margin: 0; padding: 0; line-height: 1;"><code class="python" id="{{ stype }}-{{ loop.index0 }}" >{{code}}</code></pre>
                                        {% endfor %}
                                    {% endif %}
                                </p>
                            </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>
                                        <div class="d-flex gap-2 ms-auto">
                                            <button id="pause-resume" class="btn btn-info text-white" data-bs-toggle="tooltip" title="Pause execution">
                                                {% if pause_status %}
                                                    <i class="bi bi-play-circle"></i> <!-- Icon for Pause -->
                                                {% else %}
                                                    <i class="bi bi-pause-circle"></i> <!
                                                {% endif %}
                                            </button>
                                            <button id="abort-current" class="btn btn-danger text-white" data-bs-toggle="tooltip" title="Stop execution after current step">
                                                <i class="bi bi-stop-circle"></i> <!-- Icon for Stop After This Step -->
                                            </button>
                                            <button id="abort-pending" class="btn btn-warning text-white" data-bs-toggle="tooltip" title="Stop execution after current iteration">
                                                <i class="bi bi-hourglass-split"></i> <!-- Icon for Stop After This Iteration -->
                                            </button>
                                        </div>
                                    </div>
                                    <div class="text-muted mt-2">
                                        <small><strong>Note:</strong> The current step cannot be paused or stopped until it completes. </small>
                                    </div>

                                <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">
                    {% set labels = {
                        'prep': 'Preparation:',
                        'script': 'Experiment:',
                        'cleanup': 'Clean up:'
                    } %}
                    {% for key, buttons in design_buttons.items() %}
                        {% if buttons %}
                            <h6>
                                {{labels[key]}}
                            </h6>
                            <ul>
                            {% for button in buttons %}
                            <li id="{{ button['id'] }}" style="list-style-type: none;">
                            <button type="button" class="btn btn-light" style="{{ button['style'] }}">{{ button['label'] }}</button>
                            </li>
                            {% 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">
                    {% for stype, script in dot_py.items() %}
                        <pre><code class="python" >{{script}}</code></pre>
                    {% endfor %}
                    <a href="{{ url_for('design.download', filetype='python') }}">Download <i class="bi bi-download"></i></a>
                </div>
            </div>
        </div>
    </div>

    <!-- Error Modal -->
    <div class="modal fade" id="error-modal" tabindex="-1" aria-labelledby="errorModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="errorModalLabel">Error Detected</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <p id="error-message">An error has occurred.</p>
            <p>Do you want to continue execution or stop?</p>
          </div>
          <div class="modal-footer">
              <button type="button" class="btn btn-primary" id="retry-btn" data-bs-dismiss="modal">Rerun Current Step</button>
              <button type="button" class="btn btn-success" id="continue-btn" data-bs-dismiss="modal">Continue</button>
              <button type="button" class="btn btn-danger" id="stop-btn" data-bs-dismiss="modal">Stop Execution</button>
          </div>
        </div>
      </div>
    </div>


    <script src="{{ url_for('static', filename='js/socket_handler.js') }}"></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>
    <script>
         // Initially add 5 rows when the page loads
        document.addEventListener("DOMContentLoaded", function() {
            for (let i = 0; i < 5; i++) {
                addRow();
            }
        });
    </script>
{% endblock %}
