<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={server}>
    </label>
    <button type="button" id="login-server-submit" class="btn variant-filled-primary my-3" on:click={handleSelectServer}>Submit</button>
</form>

<style lang="scss">

</style>

<script lang="js">
    import { urls, serverurl } from "../../stores.js";
    import { createEventDispatcher } from 'svelte';
    import { goto } from "$app/navigation";

    const dispatch = createEventDispatcher();

    var server = '';
    function handleSelectServer() {
        if(!isValidHttpUrl(server)) {
            server = 'https://' + server;
            if(!isValidHttpUrl(server)) {
                return dispatch('message', {text: 'This server is not a Blackbird Chess server'})
            }
        }
        console.log("Selected server: " + server);
        fetch(server + urls.capabilities)
            .then((response) => {
                if (!response.ok) return dispatch('message', {text: 'This server is not a Blackbird Chess server'})
                return response.json()
            })
            .then((data) => {
                if(!data.login) return dispatch('message', {text: 'This server is unavailable for login currently'})
                serverurl.update(n => server);
                goto('/login')
            })
            .catch((error) => {
                return dispatch('message', {text: 'This server is not a Blackbird Chess server'})
            });
    }

    function isValidHttpUrl(string) {
        let url;
        try {
            url = new URL(string);
        } catch (_) {
            return false;
        }
        return url.protocol === "http:" || url.protocol === "https:";
    }
</script>