{% extends "layouts/base.html" %}
{% from 'helpers/_forms.html' import render_field %}

{% block title %} Edit Stack {% endblock %}

<!-- Specific Page CSS goes HERE  -->
{% block stylesheets %}{% endblock stylesheets %}
{% block content %}
<main class="content">

    {% include 'includes/navigation.html' %}

    <div class="py-4">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb breadcrumb-dark breadcrumb-transparent">
                <li class="breadcrumb-item"><a href="#"><span class="fas fa-home"></span></a></li>
                <li class="breadcrumb-item"><a href="/stacks-list.html">Stack</a></li>
                <li class="breadcrumb-item active" aria-current="page">Edit</li>
            </ol>
        </nav>
        <div class="d-flex justify-content-between w-100 flex-wrap">
            <div class="mb-3 mb-lg-0">
                <h1 class="h4">Stack Edit</h1>
            </div>
            <div>
                <a href="" class="btn btn-outline-gray"><i class="far fa-question-circle mr-1"></i> Stack Docs</a>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12 mb-4">
            <div class="card border-light shadow-sm components-section">
                <div class="card-body">
                    <div class="row mb-4">
                        <div class="col-lg-4 col-sm-6">
                            <!-- Form -->
                            <div class="col-md-12 col-md-offset-1">
                                <h3>{{stack.stack_name}}</h3>
                                <form class="" id="stackForm" method="post" onsubmit="return checkForm(this);">
                                    <div class="form-group">
                                        {{ render_field(form.name, autocomplete="off", class='form-control', value=stack.stack_name) }}
                                    </div>

                                    <div class="form-group">
                                        {{ render_field(form.git, autocomplete="off", class='form-control', value=stack.git_repo) }}
                                    </div>

                                    <div class="form-group">
                                        {{ render_field(form.branch, autocomplete="off", class='form-control', value=stack.branch) }}
                                    </div>

                                    <div class="form-group">
                                        {{ render_field(form.squad_access_edit, autocomplete="off", class='form-control', value=stack.squad_access|join(',')) }}
                                    </div>

                                    <div class="form-group">
                                        {{ render_field(form.iac_type, id='iacTypeSelector',autocomplete="off", class='form-control', value=stack.iac_type) }}
                                    </div>

                                    <div class="form-group">
                                        {{ render_field(form.tf_version, id='versionSelector',autocomplete="off", class='form-control', value=stack.tf_version) }}
                                    </div>

                                    <div class="form-group">
                                        {{ render_field(form.project_path, autocomplete="off", class='form-control', value=stack.project_path) }}
                                    </div>

                                    <div class="form-group">
                                        {{ render_field(form.description, autocomplete="off", class='form-control',value=stack.description) }}
                                    </div>

<div class="form-group">
    <label for="iconSelector">Choose an Icon:</label>
    <select id="iconSelector" name="icon_path" class="form-control" onchange="previewIcon()">
        {% for category, icons in icons.items() %}
            {% for icon in icons %}
                {% set fullIconPath = '/static/assets/img/gallery/' ~ category ~ '/' ~ icon %}
                <option value="{{ fullIconPath }}" {% if fullIconPath == stack.icon_path %} selected {% endif %}>
                    {{ category }}/{{ icon }}
                </option>
            {% endfor %}
        {% endfor %}
    </select>
    <div id="iconPreview" class="mt-2">
        <!-- Icon preview will be displayed here -->
    </div>
</div>
<form class="" id="stackForm" method="post" onsubmit="return checkForm(this);">
    <input type="hidden" id="preferredView" name="preferredView">
    <input class="btn btn-primary" type="submit" name="stackButton" value="Update Stack">
</form>


                                </form>
                            </div>

                            <!-- End Form -->

                            <div class="input-group">
                            </div>
                        </div>
                    </div>
                </div>

                {% include 'includes/footer.html' %}

</main>

{% endblock content %}

<!-- Specific Page JS goes HERE  -->
{% block javascripts %}
<script type="text/javascript">
    function checkForm(form) {
        form.stackButton.disabled = true;
        form.stackButton.value = "Please wait...";
        document.getElementById('preferredView').value = localStorage.getItem('preferredView');
        return true;
    }
</script>

<script type="text/javascript">
    // This script is for populating and previewing icons.
    // Make sure the corresponding elements and event handlers are defined in your HTML.
    document.addEventListener('DOMContentLoaded', function () {
        var iconsBasePath = '/static/assets/img/gallery/';
        var iconsData = {{ icons | safe }};
        var selector = document.getElementById('iconSelector');
        var preview = document.getElementById('iconPreview');

        // Function to preview selected icon
        window.previewIcon = function() {
            var selectedIcon = selector.value;
            preview.innerHTML = '<img src="' + selectedIcon + '" alt="Icon Preview" style="max-width:100px;"/>'; // Adjust size as needed
        };

        // Call previewIcon when the page loads to show the currently selected icon
        previewIcon();
    });
</script>

<script type="text/javascript">
    // This script is for fetching release versions based on IaC type and updating the version selector.
    function fetchReleaseVersions(repoUrl) {
        return fetch(repoUrl)
            .then(response => response.json())
            .then(data => data.map(release => release.tag_name));
    }

    function updateVersionOptions(iacType, callback) {
        let repoUrl;
        switch(iacType) {
            case 'terraform':
                repoUrl = 'https://api.github.com/repos/hashicorp/terraform/releases';
                break;
            case 'terragrunt':
                repoUrl = 'https://api.github.com/repos/gruntwork-io/terragrunt/releases';
                break;
            // Ensure the case matches the actual string used for openTofu
            case 'tofu': // Adjust this case as necessary
                repoUrl = 'https://api.github.com/repos/opentofu/opentofu/releases';
                break;
            default:
                return;
        }

        fetchReleaseVersions(repoUrl).then(versions => {
            const versionSelector = document.getElementById('versionSelector');
            versionSelector.innerHTML = '';

            versions.forEach(version => {
                const option = document.createElement('option');
                option.value = version;
                option.text = version;
                versionSelector.appendChild(option);
            });

            if(callback) callback();
        });
    }

    function setInitialVersions(iacType, initialVersion) {
        updateVersionOptions(iacType, function() {
            const versionSelector = document.getElementById('versionSelector');
            versionSelector.value = initialVersion;
        });
    }

    document.addEventListener('DOMContentLoaded', function () {
        const iacTypeSelector = document.getElementById('iacTypeSelector'); 
        const initialIacType = '{{ stack.iac_type }}';
        const initialVersion = '{{ stack.tf_version }}';

        iacTypeSelector.value = initialIacType;
        setInitialVersions(initialIacType, initialVersion);

        iacTypeSelector.addEventListener('change', function() {
            updateVersionOptions(this.value);
        });
    });
</script>
{% endblock javascripts %}

