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

{% block submit_buttons_bottom %}

    {{ block.super }}
    <div class="submit-row">
        {% if not add %}
            {% if request.is_secure or "127.0.0.1" in request.get_host or "localhost" in request.get_host %}
                <input type="button" value="Copy" onclick='generateValues("copy")'>
            {% else %}
                {% if info %}
                    <input type="button" value="Copy" onclick="copyToClipboard()">
                {% else %}
                    <input type="button" value="Generate" onclick='generateValues("generate")'>
                {% endif %}
            {% endif %}

        {% 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 secureCopyToClipboard() {
        let copyText = document.getElementById("copyTextarea");
        navigator.clipboard.writeText(copyText.value);
    }

    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");
        let copyButton = document.getElementById("copyButton");
        if (copyText && copyText.value)
            navigator.clipboard.writeText(copyText.value).catch(err => {})
    });

</script>
{% endblock %}
