<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={loginserver}>
    </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 } from "../../../stores.js";
    import {createEventDispatcher, onMount} from 'svelte';
    import {browser} from "$app/environment";
    import { requestor, setBaseUrl } from "../../../serverrequest.js";

    export let globals;

    var loginserver;
    const dispatch = createEventDispatcher();

    onMount(() => {
        if(sessionStorage.getItem('serverurl') != undefined) {
            loginserver = sessionStorage.getItem('serverurl');
            handleSelectServer();
        }
    })

    async function handleSelectServer() {
        if(!isValidHttpUrl(loginserver)) {
            loginserver = 'https://' + loginserver;
            if(!isValidHttpUrl(loginserver)) {
                return dispatch('message', {text: 'This server is not a Blackbird Chess server'})
            }
        }
        console.log("Selected server: " + loginserver);
        setBaseUrl(loginserver);

        try {
            let response = await requestor.get(urls.capabilities);
            let data = JSON.parse(response.data);
            if(!data.login) return dispatch('message', {text: 'This server is unavailable for login currently'})
            globals.server.url = loginserver;
            globals.server.caps = data;
            if(browser) {
                sessionStorage.setItem('serverurl', loginserver);
            }
        } 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>