{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Decrypt and Forward</title>
    <script src="{% static 'abac/jsbn.js' %}"></script>
    <script src="{% static 'abac/jsbn2.js' %}"></script>
    <script src="{% static 'abac/prng4.js' %}"></script>
    <script src="{% static 'abac/rng.js' %}"></script>
    <script src="{% static 'abac/paillier.js' %}"></script>
</head>
<body>
    <script>

        function getPrivateKeyFromWebStorage() {
            // Retrieve and parse the stored private key
            const storedPrivateKey = localStorage.getItem('privateKey');
            if (!storedPrivateKey) return null;

            const parsedKey = JSON.parse(storedPrivateKey);

            // Construct the public key from the stored value
            const n = new BigInteger(localStorage.getItem('publicKey'));
            const publicKey = new paillier.publicKey(2048, n);

            // Construct the private key
            const lambda = new BigInteger(parsedKey.lambda);
            const privateKey = new paillier.privateKey(lambda, publicKey);
            
            // Attach the x value
            privateKey.x = new BigInteger(parsedKey.x);

            return privateKey;
        }

        // Assuming you have a method to get privateKey from local web storage
        let privateKey = getPrivateKeyFromWebStorage(); 

        let encryptions = {{ encryptions_as_strings|safe }};
        let decryptedValues = [];
            
        for(let enc of encryptions) {
            let bigIntEnc = new BigInteger(enc.toString());
            decryptedValues.push(privateKey.decrypt(bigIntEnc).toString(10));
        }

        // Forward the decrypted values with a POST request
        let form = document.createElement("form");
        form.setAttribute("method", "post");
        form.setAttribute("action", "{% url 'abac:verify_decryption' %}");
        
        let csrfField = document.createElement("input");
        csrfField.setAttribute("type", "hidden");
        csrfField.setAttribute("name", "csrfmiddlewaretoken");
        csrfField.setAttribute("value", "{{ csrf_token }}");
        form.appendChild(csrfField);

        let tokenField = document.createElement("input");
        tokenField.setAttribute("type", "hidden");
        tokenField.setAttribute("name", "token");
        tokenField.setAttribute("value", "{{ token }}");
        form.appendChild(tokenField);
        
        for(let dec of decryptedValues) {
            let input = document.createElement("input");
            input.setAttribute("type", "hidden");
            input.setAttribute("name", "decryptions");
            input.setAttribute("value", dec);
            form.appendChild(input);
        }

        document.body.appendChild(form);
        form.submit();
    </script>
</body>
</html>