{% extends "base.html" %}
{% block head %}
    <link rel="stylesheet"
          type="text/css"
          href="https://cdn.datatables.net/2.2.1/css/dataTables.dataTables.min.css">
    <link rel="stylesheet"
          type="text/css"
          href="https://cdn.datatables.net/select/3.0.0/css/select.dataTables.min.css">
    <link rel="stylesheet"
          type="text/css"
          href="https://cdn.datatables.net/2.2.1/css/dataTables.bootstrap5.css">
{% endblock %}
{% block title %}Home - Ingenious Prompt Tuner{% endblock %}
{% block content %}
    <br />
    <div class="alert alert-primary alert-dismissible fade show" role="alert">
        <h4 class="alert-heading">Welcome</h4>
        <button type="button"
                class="btn-close"
                data-bs-dismiss="alert"
                aria-label="Close"></button>
        <p>
            This is the the home page of the Ingenious prompt tuning application. It is a development tool designed to help
            you iterate and ideate on AI agent prompts quickly and efficiently.
        </p>
        <p>Revisions folder is: {{ base_folder }}.</p>
    </div>
    <p></p>
    <p class="lead" id="selectedRevisionNotice">To begin select a revision from the list below.</p>
    <div class="btn-group" role="group" aria-label="Revision Actions">
        <button id="createRevisionButton"
                onclick="javascript"
                :window.open
                '
                {{ url_for("index.create_revision") }}
                '
                class="btn btn-outline-primary"
                disabled>
            <i class="bi bi-copy"></i> Copy Selected Revision
        </button>
        <button id="syncSampleData"
                onclick="SyncSampleData()"
                class="btn btn-outline-warning"
                disabled>
            <i class="bi bi-arrow-repeat"></i> Sync Sample Data
            <span id="syncSampleDataSpinner"
                  class="spinner-border spinner-border-sm"
                  role="status"
                  aria-hidden="true"
                  style="display: none"></span>
        </button>
        <button id="syncPrompts"
                onclick="SyncPrompts()"
                class="btn btn-outline-warning"
                disabled>
            <i class="bi bi-arrow-repeat"></i> Sync Prompts
            <span id="syncPromptsSpinner"
                  class="spinner-border spinner-border-sm"
                  role="status"
                  aria-hidden="true"
                  style="display: none"></span>
        </button>
        <button id="clearCookiesButton"
                onclick="clearCookies()"
                class="btn btn-outline-danger">
            <i class="bi bi-trash"></i> Clear Selection
        </button>
    </div>
    <table id="revisionsTable" class="display">
        <thead>
            <tr>
                <th>Revision Name</th>
                <th>Revision Description</th>
            </tr>
        </thead>
        <tbody>
            {% for revision in files %}
                <tr>
                    <td>{{ revision.name }}</td>
                    <td>{{ revision.description }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
{% endblock %}
{% block scripts %}
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript"
            charset="utf8"
            src="https://cdn.datatables.net/2.2.1/js/dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/select/3.0.0/js/dataTables.select.min.js"></script>
    <script src="https://cdn.datatables.net/select/3.0.0/js/select.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/2.2.1/js/dataTables.bootstrap5.js"></script>
    <script>
    function clearCookies() {
        document.cookie.split(";").forEach(function (c) {
            document.cookie = c.trim().split("=")[0] + '=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/';
        });
        location.reload();
    }

    async function UpdateButtonState() {
        // Automatically select the record if a revision is stored in cookies
        const selectedRevision = await getSelectedRevision('selected_revision');

        if (selectedRevision) {
            $('#createRevisionButton').removeAttr('disabled');
            $('#syncSampleData').removeAttr('disabled');
            $('#syncPrompts').removeAttr('disabled');
            document.getElementById('editPromptsNav').style.display = 'block';
            document.getElementById('runTestsNav').style.display = 'block';
        }
        else {
            $('#createRevisionButton').prop('disabled', true);
            $('#syncSampleData').prop('disabled', true);
            $('#syncPrompts').prop('disabled', true);
            document.getElementById('editPromptsNav').style.display = 'none';
            document.getElementById('runTestsNav').style.display = 'none';
        }


    }

    function SyncPrompts() {
        const syncButton = document.getElementById('syncPrompts');
        const spinner = document.getElementById('syncPromptsSpinner');
        spinner.style.display = 'inline-block';
        syncButton.disabled = true;
        var url = "{{ url_for('index.sync_prompts') }}";

        fetch(url, {
            method: 'GET'
        })
            .then(response => {
                if (response.ok) {
                    alert('Prompts synced successfully');
                } else {
                    alert('Failed to sync prompts');
                }
            })
            .finally(() => {
                spinner.style.display = 'none';
                syncButton.disabled = false;
            });
    }

    function SyncSampleData() {
        const syncButton = document.getElementById('syncSampleData');
        const spinner = document.getElementById('syncSampleDataSpinner');
        spinner.style.display = 'inline-block';
        syncButton.disabled = true;
        var url = "{{ url_for('index.sync_sample_data') }}";

        fetch(url, {
            method: 'GET'
        })
            .then(response => {
                if (response.ok) {
                    alert('Sample data synced successfully');
                } else {
                    alert('Failed to sync sample data');
                }
            })
            .finally(() => {
                spinner.style.display = 'none';
                syncButton.disabled = false;
            });
    }

    function OpenUrl(url) {
        window.location.href(url);
    }



    async function getSelectedRevision(name) {
        return fetch("{{ url_for('index.get_selected_revision') }}", {
            method: 'GET'
        })
            .then(response => {
                if (response.ok) {
                    return response.json().then(data => {
                        return data.revision;
                    });
                } else {
                    alert('Failed to get selected cookie');
                    return null;
                }
            });
    }

    async function setSelectedRevision(revision_id) {
        return fetch(`{{ url_for('index.set_selected_revision') }}?revision_id=${revision_id}`, {
            method: 'GET'
        })
            .then(response => {
                if (response.ok) {
                    return null;
                } else {
                    alert('Failed to get selected cookie');
                    return null;
                }
            });
    }



    $(document).ready(async function () {
        table = $('#revisionsTable').DataTable({
            select: {
                style: 'single'
            },
            pageLength: 100
        });

        table.on('select', function (e, dt, type, indexes) {
            let rowData = table
                .rows(indexes)
                .data()
                .toArray();

            var revisionName = rowData[0][0];
            var revisionTitle = rowData[0][1];
            setSelectedRevision(revisionName).then(() => {
                notice = 'The currently selected revision is <mark>' + revisionName + " -- " + revisionTitle + '</mark>'
                $('#selectedRevisionNotice').html(notice)
                UpdateButtonState().then(() => {
                    // Additional actions if needed after button state update
                });
            });

        });

        const selectedRevision = await getSelectedRevision('selected_revision');
        if (selectedRevision) {
            table.rows().every(function () {
                var data = this.data();
                if (data[0] === selectedRevision) {
                    this.select();
                    UpdateButtonState().then(() => {
                        // Additional actions if needed after button state update
                    });
                }
            });
        }


    });



    </script>
{% endblock %}
