<div class="container h-full mx-auto flex justify-center items-center flex-col">
    <h1 class="my-3">Blackbird Chess</h1>


    {#if message.visible}
        <aside class="alert variant-filled-error">
            <!-- Icon -->
            <div><i class="text-2xl icon icon-exclamation-triangle"></i></div>
            <!-- Message -->
            <p class="alert-message">{message.text}</p>
            <!-- Actions -->
            <div class="alert-actions">
                <i on:click={closeWarning} class="icon icon-close"></i>
            </div>
        </aside>
    {/if}

    <form name="login-server" class="flex flex-col">
        <label class="label my-3">
            <span>Please select the server to login:</span>
            <input
                    type="url"
                    name="server"
                    id="login-server-url"
                    class="input"
                    bind:value={serverurl}>
        </label>
        <button type="button" id="login-server-submit" class="btn variant-filled-primary my-3" on:click={handleSelectServer}>Submit</button>
    </form>
</div>

<style lang="scss">

</style>

<script lang="js">
    import { urls, server } from "../stores.js";
    import {goto} from "$app/navigation";
    let message = {
        visible: false,
        text: '',
        class: 'error'
    };
    var serverurl = '';
    function handleSelectServer() {
        console.log("Selected server: " + serverurl);
        fetch(serverurl + urls.capabilities)
            .then((response) => {
                if (!response.ok) return unavailableServer('This server is not a Blackbird Chess Server')
                return response.json()
            })
            .then((data) => {
                if(!data.login) return unavailableServer('This server is unavailable for login currently');
                server.update(n => serverurl);
                goto('/login')
            })
    }

    function unavailableServer(error) {
        console.log(error);
        message.text = error;
        message.class = 'error'
        message.visible = true;
    }

    function closeWarning() {
        message.visible = false;
    }
</script>