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

    var loginserver;

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


    async function handleSelectServer() {
        if(!isValidHttpUrl(loginserver)) {
            loginserver = 'https://' + loginserver;
            if(!isValidHttpUrl(loginserver)) {
                return alerts.update(data => [...data, {text: loginserver + ' is not a Blackbird Chess server', class: 'error'}]);
            }
        }
        console.log("Selected server: " + loginserver);
        setBaseUrl(loginserver);

        try {
            let response = await requestor.get(urls.capabilities);
            let caps = JSON.parse(response.data);
            if(!caps.login) return alerts.update(data => [...data, {text: loginserver + ' is unavailable for login currently', class: 'error'}]);
            globals.update(data => ({ ...data, ...{server: {url: loginserver, caps: caps}}}));
            if(browser) {
                sessionStorage.setItem('serverurl', loginserver);
            }
        } catch (error) {
            return alerts.update(data => [...data, {text: loginserver + ' is not a Blackbird Chess server', class: 'error'}]);
        }
    }


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