{% load ocyan_main %}
{% comment %}
    The docs state the following: "reCAPTCHA tokens expire after two minutes. If you're protecting an action with reCAPTCHA, make sure to call execute when the user takes the action rather than on page load."

    The default captcha implementation executes on page load, which, as said above shouldn't be.
    
    This template is overridden so it generates a new key every 110 seconds (less than 2 minutes) because we don't know when and which form is being submitted that has a captcha. We also support multiple captcha's per
    page by passing the widget_uuid to the updateCaptcha function so it updates the correct captcha widget. And at last we make sure the google recaptcha script will only be loaded once in the DOM.

    Solution from: https://github.com/praekelt/django-recaptcha/issues/183#issuecomment-616767858
{% endcomment %}

<script type="text/javascript" nonce="{% nonce %}">
    var captchaUrl = "https://{{ recaptcha_domain }}/recaptcha/api.js?render={{ public_key }}{% if api_params %}&{{ api_params }}{% endif %}";
    var recaptchaScriptID = "recaptcha-script";

    // Adds the captcha JS if it doesn't exist yet.
    if (document.getElementById(recaptchaScriptID) === null) {
        let script = document.createElement('script');
        script.src = captchaUrl;
        script.id = recaptchaScriptID; // Add ID so we can add an load event listener.
        document.getElementsByTagName('head')[0].appendChild(script);
    }

    // Once the script is actually loaded, excecute the captcha ready function.
    document.getElementById("recaptcha-script").addEventListener("load", function() {
        grecaptcha.ready(function() {
          updateCaptcha("{{ widget_uuid }}");
          setInterval(updateCaptcha, 110000, "{{ widget_uuid }}");
        });
    });

    function updateCaptcha(widget_uuid) {
      grecaptcha.execute('{{ public_key }}', {action: 'form'})
        .then(function(token) {
            console.log("reCAPTCHA validated for 'data-widget-uuid=" + widget_uuid + "'. Setting input value...")
            var elements = document.querySelectorAll('.g-recaptcha[data-widget-uuid="' + widget_uuid + '"]');
            elements.forEach(function(element) {
                element.value = token;
            });
        });
    }
</script>
