<div class="flex justify-between">
    <a href="/account/login">Go Back</a>
</div>
{#if globalvars.server.caps.register }
    <form name="login-server" class="flex flex-col">
        <label class="label my-3">
            <span>Username:</span>
            <input bind:value="{name}" on:input="{triggerCheck}" type="text" name="email" id="register-name" class="input">
        </label>
        <label class="label my-3">
            <span>E-mail:</span>
            <input bind:value="{email}" on:input="{triggerCheck}" type="email" name="email" id="register-email" class="input">
        </label>
        <label class="label my-3">
            <span>Password:</span>
            <input bind:value={password} on:input="{triggerCheck}" type="password" name="password" id="register-password" class="input">
        </label>
        <label class="label my-3">
            <span>Repeat password:</span>
            <input bind:value={password2} on:input="{triggerCheck}" type="password" name="password2" id="register-password-repeat" class="input">
        </label>
        <button on:click="{register}"type="submit" id="register-server-submit" class="btn variant-filled-primary my-3">Register</button>
    </form>
{/if}


<style lang="scss">

</style>

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

    let globalvars;
    let email = '';
    let name = '';
    let password = '';
    let password2 = '';

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

    setBaseUrl(globalvars.server.url);

    onMount(async () => {
        if(globalvars.server.url == '' ) {
            alerts.update(data => data.filter(alert => alert.type !== 'noregister'));
            alerts.update(data => [...data,{text: 'You cannot register without selecting a server', type: 'noregister', class: 'error'}]);
            goto('/account/login');
            return;
        }
        if(globalvars.server.caps.register == false ) {
            alerts.update(data => data.filter(alert => alert.type !== 'noregister'));
            alerts.update(data => [...data,{text: 'You cannot register on this server', type: 'noregister', class: 'error'}]);
        }
    })
    function triggerCheck(evt) {
        switch(evt.target.id) {
            case 'register-name':
                checkName(false);
                break;
            case 'register-email':
                checkEmail(false);
                break;
            case 'register-password':
            case 'register-password-repeat':
                checkPassword(false);
                break;
        }
    }
    async function checkEmail(errorempty = false) {
        if (email.length == 0) {
            alerts.update(data => data.filter(alert => alert.type !== 'emailtaken'));
            if(errorempty) alerts.update(data => [...data,{text: 'Email cannot be empty', type: 'emailtaken', class: 'error'}]);
            return false
        }
        if(document.querySelector('#register-email').checkValidity() === false) {
            alerts.update(data => data.filter(alert => alert.type !== 'emailtaken'));
            if(errorempty) alerts.update(data => [...data,{text: 'Email is invalid', type: 'emailtaken', class: 'error'}]);
            return false;
        }
        try {
            let response = await requestor.post(urls.checkusertaken, JSON.stringify({ email: email }));
            let data = JSON.parse(response.data);
            if(typeof data.email == 'undefined') {
                alerts.update(data => data.filter(alert => alert.type !== 'emailtaken'));
                return true
            }
            if(data.email == 'taken') {
                alerts.update(data => data.filter(alert => alert.type !== 'emailtaken'));
                alerts.update(data => [...data, {text: 'Email is already taken', type: 'emailtaken', class: 'error'}]);
                return false;
            }
        } catch (error) {
            alerts.update(data => [...data, {text: 'Server unavailable', type: 'noserveravailable', class: 'error'}]);
            return false;
        }
    }

    async function checkName(errorempty = false) {
        if (name.length == 0) {
            if(errorempty) alerts.update(data => [...data,{text: 'Username cannot be empty', type: 'usernametaken', class: 'error'}]);
            return false
        }
        if(document.querySelector('#register-name').checkValidity() === false) {
            alerts.update(data => data.filter(alert => alert.type !== 'usernametaken'));
            if(errorempty) alerts.update(data => [...data,{text: 'Username cannot be empty', type: 'usernametaken', class: 'error'}]);
            return false;
        }
        try {
            let response = await requestor.post(urls.checkusertaken, JSON.stringify({ name: name }));
            let data = JSON.parse(response.data);
            if(typeof data.name == 'undefined') {
                alerts.update(data => data.filter(alert => alert.type !== 'usernametaken'));
                return true;
            }
            if(data.name == 'taken') {
                alerts.update(data => data.filter(alert => alert.type !== 'usernametaken'));
                alerts.update(data => [...data,{text: 'Username is already taken', type: 'usernametaken', class: 'error'}]);
                return false
            }
        } catch (error) {
            alerts.update(data => [...data, {text: 'Server unavailable', type: 'noserveravailable', class: 'error'}]);
            return false
        }
    }

    async function checkPassword(errorempty = false) {
        if (password == '') {
            alerts.update(data => data.filter(alert => alert.type !== 'passwordnotequal'));
            if(errorempty) alerts.update(data => [...data,{text: 'Password cannot be empty', type: 'passwordnotequal', class: 'error'}]);
            return false

        }
        if (password2 == '') {
            alerts.update(data => data.filter(alert => alert.type !== 'passwordnotequal'));
            if(errorempty) alerts.update(data => [...data,{text: 'Password cannot be empty', type: 'passwordnotequal', class: 'error'}]);
            return false
        }
        if (password != password2) {
            alerts.update(data => data.filter(alert => alert.type !== 'passwordnotequal'));
            alerts.update(data => [...data,{text: 'Passwords are not equal', type: 'passwordnotequal', class: 'error'}]);
            return false
        } else {
            alerts.update(data => data.filter(alert => alert.type !== 'passwordnotequal'));
            return true
        }
    }
    async function register() {
        let emailok = await checkEmail(true);
        let nameok = await checkName(true);
        let passwordok = await checkPassword(true);
        alerts.update(data => data.filter(alert => alert.type !== 'register-errors'));

        if(!(emailok && nameok && passwordok )) {
            alerts.update(data => [...data, {text: 'Errors in fields, please check', type: 'register-errors', class: 'error'}]);
            return false;
        }

        try {
            let response = await requestor.post(urls.register, JSON.stringify({ email: email, name: name, password: password }));
            let responsejson = JSON.parse(response.data);
            if (response.status !== 200) {
                alerts.update(data => data.filter(alert => alert.type !== 'register-errors'));
                alerts.update(data => [...data, {text: responsejson.Message, type: 'register-errors', class: 'error'}]);
                return false;
            }
            alerts.update(data => []);
            alerts.update(data => [...data, {text: responsejson.Message, type: 'register-success', class: 'success'}]);
            return false;
        } catch (error) {
            alerts.update(data => [...data, {text: 'Server unavailable', type: 'noserveravailable', class: 'error'}]);
            return false;
        }
    }
</script>