<script>
    import { onMount }       from 'svelte';
    import { useTinyRouter } from 'svelte-tiny-router';

    import { api }                 from '../urls.svelte';
    import { error, yikes }        from '../warn.svelte';
    import { checkUser, tryLogin } from '../user.svelte';
    import { t }                   from '../translations.svelte';

    let credentials = $state({ username : null, password : null });
    const router    = useTinyRouter();
    let services    = $state([]);

    async function doLogin(ev){
        ev.preventDefault();
        const json = await tryLogin(credentials);
        if (json) {
            json.release_time = json.release_time.replace('T',' ');
            error(t('failed_login_attempts',json));
        }
    }

    function init(element){
        element.focus();
    }

    async function load(){
        await checkUser();
        const url  = api('user/oidc/buttons');
        const resp = await fetch(url,{credentials:'include'});
        if (resp.ok){
            const json = await resp.json();
            for (let service of json) services.push(service);
        }
    }


    async function redirectTo(e,service){
        const btn = e?.target;
        if (btn) btn.disabled = true;
        const url  = api(`user/oidc/redirect/${service}?returnTo=${encodeURIComponent(window.location.pathname)}`);
        const resp = await fetch(url,{credentials:'include'});
        if (resp.ok){
            const json = await resp.json();
            yikes();
            if (json.authorization_endpoint) {
                const endpoint = json.authorization_endpoint;
                delete json.authorization_endpoint;
                location.href = endpoint + '?' + new URLSearchParams(json);
            }
        } else {
            error(resp);
            if (btn) btn.disabled = false;
        }
    }

    function resetPW(ev){
        ev.preventDefault();
        router.navigate('/user/reset/pw');
    }

    if (router.fullPath.endsWith('/openid_login') && router.query.service) {
        redirectTo(null,router.query.service);
    } else {
        onMount(load);
    }
</script>

<style>
    label { display: block; margin: 5px; }
    fieldset {
        display: block;
        position: relative;
        left: 50%;
        width: 200px;
        margin-left: -100px;
        margin-bottom: 30px;
        text-align: center;
    }
    a{
        display: block;
        margin-top: 15px;
    }
</style>

<form onsubmit={doLogin}>
    <fieldset>
        <legend>{t('login')}</legend>
        <label>
            <input type="text" bind:value={credentials.username} required use:init />
            <span>{t('email_or_username')}</span>
        </label>
        <label>
            <input type="password" bind:value={credentials.password} required />
            <span>{t('password')}</span>
        </label>
        <button>{t('do_login')}</button>
        <a onclick={resetPW}>{t('forgot_pass')}</a>
    </fieldset>
</form>
<fieldset>
    <legend>{t('oidc_Login')}</legend>
    {#each services as service,i}
    <button onclick={e => redirectTo(e,service)}>{service}</button>
    {/each}
</fieldset>
