{% extends "admin/change_form.html" %}

{% block submit_buttons_bottom %}

    {{ block.super }}
    <div class="submit-row">
        {% if not add %}
            <input type="button" id="dynamicButton" value="Generate" onclick='generateValues("generate")'>
        {% else %}
            <input type="button" value="Paste" onclick="pasteValues()">
        {% endif %}
        <textarea id="copyTextarea" style="display: none;">{{ info }}</textarea>
    </div>


<script>
    function pasteValues() {
        let currentUrl = new URL(window.location.href);
        currentUrl.searchParams.set('paste', 'true');
        window.location.href = currentUrl.toString();
    }

    function generateValues(value) {
        let currentUrl = new URL(window.location.href);
        currentUrl.searchParams.set(value, 'true');
        window.location.href = currentUrl.toString();
    }

    function copyToClipboard() {
        let copyText = document.getElementById("copyTextarea");
        copyText.style.display = 'block';
        copyText.select();
        document.execCommand('copy');
        copyText.style.display = 'none';
        alert('Data copied successfully!');
    }

    document.addEventListener('DOMContentLoaded', (event) => {
        let copyText = document.getElementById("copyTextarea");
        if (window.location.protocol === "https:" ||
        window.location.hostname.indexOf("127.0.0.1") !== -1 || window.location.hostname.indexOf("localhost") !== -1) {
                let dynamicButton = document.getElementById("dynamicButton");
                if (dynamicButton) {
                    dynamicButton.value = "Copy";
                    dynamicButton.onclick = function() {
                        generateValues("copy");
                    }
                }
                if (copyText && copyText.value)
                    navigator.clipboard.writeText(copyText.value).catch(err => {})
        } else {
            if (copyText && copyText.value) {
                dynamicButton.value = "Copy";
                dynamicButton.onclick = function() {
                    copyToClipboard("copy");
                }
            }
        }
    });
</script>
{% endblock %}