{% load i18n %}
<script>
    const changeSecretProgressBar = document.getElementById('changeSecretProgressBar');
    const changeSecretModalContinueButton = document.getElementById('changeSecretModalContinueButton');
    const secret_placeholder = '{{ placeholder }}'
    const needsChangingWaitingTime = 5  // seconds
    var changeSecretModal = null;
    var shouldShowModal = {{ show_password_update_alert|lower }};
    const okButtonHandler = function () {
        closeModal();
    };

    function getSecret(callback) {
        if (shouldShowModal) {
            showModal();
        } else {
            $.ajax({
                url: "{{ secret_url }}",
                type: "get",
                dataType: "json",
                success: function (data) {
                    callback(data['password']);
                },
            });
        }
    }

    function getSecretSync() {
        let secret;
        $.ajax({
            url: "{{ secret_url }}",
            async: false,
            type: "get",
            dataType: "json",
            success: function (data) {
                secret = data;
            },
        });
        return secret;
    }

    function reveal(password) {
        let revBtnTooltip = bootstrap.Tooltip.getInstance('#revealButton')
        revBtnTooltip.setContent({'.tooltip-inner': '{% trans "Hide plain text" %}'})

        const revBtn = document.getElementById('revealButton')
        revBtn.setAttribute('onclick', 'unreveal()')
        revBtn.querySelector('i').classList.remove('fa-magic')
        revBtn.querySelector('i').classList.add('fa-shield')

        let passwordField = document.getElementById('password-field')
        const passwordHTML = teamvault.getColorfulPasswordHTML(password);
        passwordField.replaceChildren(...passwordHTML)
    }

    function unreveal() {
        let revBtnTooltip = bootstrap.Tooltip.getInstance('#revealButton')
        revBtnTooltip.setContent({'.tooltip-inner': '{% trans "Reveal as plain text" %}'})

        const revBtn = document.getElementById('revealButton')
        revBtn.setAttribute('onclick', 'getSecret(reveal)');
        revBtn.querySelector('i').classList.remove('fa-shield')
        revBtn.querySelector('i').classList.add('fa-magic')

        let passwordField = document.getElementById('password-field')
        passwordField.replaceChildren(document.createTextNode(secret_placeholder))
    }

    function initProgressBar() {
        changeSecretProgressBar.animate(
            {width: ["0%", "100%"]},
            {duration: needsChangingWaitingTime * 1000, fill: "forwards"}
        )
    }

    function showModal() {
        changeSecretModal = new bootstrap.Modal('#changeSecretModal');
        changeSecretModal.show();

        initProgressBar();
        window.setTimeout(
            () => {
                changeSecretModalContinueButton.style.display = '';
                changeSecretProgressBar.parentElement.remove()
            },
            needsChangingWaitingTime * 1000
        );
        shouldShowModal = false;
    }

    function closeModal() {
        changeSecretModal.hide();
        document.getElementById('copy-password').removeAttribute('onclick');
        setUpPasswordClipboard();
    }

    function setUpPasswordClipboard() {
        new window.ClipboardJS("#copy-password", {
            text: function () {
                return getSecretSync()['password'];
            }
        }).on('success', function (e) {
            e.clearSelection();
            notyf.success("{% trans "Password has been copied to your clipboard." %}");
        });
    }

    function setUpOtpClipboard() {
        new window.ClipboardJS("#copy-otp", {
            text: function () {
                let otpValue = document.getElementById("otp-field").textContent;
                return otpValue;
            }
        }).on('success', function (e) {
            e.clearSelection();
            notyf.success("{% trans "OTP has been copied to your clipboard." %}");
        });
    }

    function setUpAdditionalClipboards() {
        new window.ClipboardJS("#copy-url").on('success', function (e) {
            e.clearSelection();
            notyf.success("{% trans "URL has been copied to your clipboard." %}");
        });

        new window.ClipboardJS("#copy-username").on('success', function (e) {
            e.clearSelection();
            notyf.success("{% trans "Username has been copied to your clipboard." %}");
        });
    }
</script>
<script>
    {% if  secret_revision and secret_revision.otp_key_set %}
        document.addEventListener('DOMContentLoaded', () => {
            const textElement = document.getElementById('otp-field');
            const countdownContainerEl = document.getElementById('countdown');
            const countdownNumberEl = document.getElementById('countdown-number');
            const bigElement = document.querySelector('.large-type');
            otp.refreshOtpEvery30Sec(textElement, "{{ secret_url }}", bigElement);
            otp.otpCountdown(countdownContainerEl, countdownNumberEl, textElement, '{{ secret_url }}', bigElement);
            setInterval(() => {
                otp.otpCountdown(
                    countdownContainerEl, countdownNumberEl,
                    textElement, '{{ secret_url }}',
                    bigElement)}, 1_000
            );
        })
    {% endif %}
</script>
