<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>

<body>
<div id="container"></div>


<script src="{{ idp_url }}/auth/js/keycloak.js"></script>
<script>

    kc = Keycloak("http://127.0.0.1:{{ port }}/keycloak.json");
    kc.init({
        onLoad: 'login-required',
        checkLoginIframe: false,
        enableLogging: true,
        pkceMethod: 'S256'

    }).success((authenticated) => {
        console.debug("Authenticated: " + authenticated);

        const accessTokenValidSec = kc.tokenParsed.exp - kc.tokenParsed.iat;
        console.debug("Access token valid for: " + accessTokenValidSec);

        const refreshTokenValidSec = kc.refreshTokenParsed.exp - kc.refreshTokenParsed.iat;
        console.debug("Refresh token valid for: " + refreshTokenValidSec);

        const tokenBody = {
            access_token: kc.token,
            access_token_valid_sec: accessTokenValidSec,
            refresh_token: kc.refreshToken,
            refresh_token_valid_sec: refreshTokenValidSec
        };

        const container = document.getElementById("container");

        fetch("http://127.0.0.1:{{ port }}/deliver-tokens", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(tokenBody)
        })
            .then(response => {
                if (response.ok) {
                    container.textContent = "{{ success_msg }}";
                    window.close();
                } else {
                    container.textContent = "{{ fail_msg }}";
                }
            });

    }).error(() => {
        console.error("Keycloak init failed");
        document.getElementById("container").textContent = "{{ fail_msg }}";
    });

</script>
</body>
</html>