<div class="flex justify-between">
    <div on:click="{handleGoToServerSelect}"><i class="text-2xl icon icon-arrow-left hover:text-primary-500"></i></div>
</div>
<form name="login-server" class="flex flex-col">
    <label class="label my-3">
        <span>E-Mail:</span>
        <input type="email" name="email" id="login-email" class="input" bind:value={email}>
    </label>
    <label class="label my-3">
        <span>Password:</span>
        <input type="password" name="password" id="login-password" class="input" bind:value={password}>
    </label>
    <button type="button" id="login-server-submit" class="btn variant-filled-primary my-3" on:click={handleLogin}>Submit</button>

    <div class="flex justify-between">
        {#if globalvars.server.caps.register }
            <a href="/account/register" class="anchor">Register</a>
        {/if}
        {#if globalvars.server.caps.reset }
            <a href="/account/reset" class="anchor">Reset your password</a>
        {/if}
    </div>

</form>

<style lang="scss">

</style>

<script lang="js">
    import { urls, alerts, globals, sessionvars } from "$lib/stores.js";
    import { browser } from "$app/environment";
    import { requestor, setBaseUrl } from "../../../serverrequest.js";
    import { goto } from "$app/navigation";

    var email = '';
    var password = '';

    let globalvars;

    globals.subscribe(value => {
        globalvars = value;
    });

    let sessions;

    sessionvars.subscribe(value => {
        sessions = value;
    });

    setBaseUrl(globalvars.server.url);

    async function handleLogin() {
        try {
            let postdata = {email: email, password: password}
            let response = await requestor.post(urls.login, JSON.stringify(postdata));
            let responsedata = JSON.parse(response.data);
            if(response.status !== 200) {
                let message = 'Something went wrong during login'
                if(typeof responsedata.message !== 'undefined') message = responsedata.message
                throw(message)
            }
            if(!responsedata.success) return alerts.update(data => [...data, {text: 'Login failed: ' + responsedata.message , class: 'error'}]);
            globals.update((globalobj) => ({ ...globalobj, ...{user: responsedata.user }}));
            sessions.update((sessionobj) => ({ ...sessionobj, ...{authorization: responsedata.authorization }}));
            goto('/')
        } catch (error) {
            return alerts.update(data => [...data, {text: error, class: 'error'}]);
        }
    }

    function handleGoToServerSelect() {
        if(typeof sessions.serverurl !== 'undefined') {
            sessionvars.update(data => { delete data.serverurl; return data;});
            globals.update((data) => ({ ...data, ...{server: {url: '', caps: {}}} }));
        }
    }
</script>