<template>
    <div class="login-wrapper">
        <div class="tile-l login-window">
            <h2>Kubooboo</h2>
            <img class="logo" src="@/assets/logo.png" alt="">
            <form class="login content-xl" @submit.prevent="doLogin()">
                <div class="center">
                    <h1>Login</h1>
                </div>
                <div class="content-l">   
                    <UiInput label="Username">
                        <input type="text" v-model="loginCredentials.username">
                    </UiInput>
                    <UiInput label="Passwort">
                        <input type="password" v-model="loginCredentials.password">
                    </UiInput>
                </div>
                <div class="center">
                    <UiButton @onclick="() => doLogin()" :loading="loading" icon="login" reverse>Login</UiButton>
                </div>
            </form>
        </div>
        
    </div>
</template>

<script setup lang="ts">
import { User } from '~/classes/User';
import UiInput from '~/components/ui/UiInput.vue';
import { login } from '~/requests/login';
import { jwtDecode } from 'jwt-decode';
import { getUser } from '~/requests/user';
import { Session } from '~/classes/Session';

const loginCredentials = ref(new User());

const loading = ref(false);
function doLogin()
{
    loading.value = true;
    login(loginCredentials.value, (token: string) => {
        const decode = jwtDecode(token) as any;
        getUser(decode.upn, token, (user: User) => {
            setSessionCookie(new Session(user, token), decode.exp as number);
            useRouter().push('/account/inspect/nodes/_all');
        });
    });
}

function setSessionCookie(session: Session, exp: number)
{
    const cookie = useCookie('session', {
        expires: new Date(exp * 1000)
    });
    cookie.value = JSON.stringify(session);
}
</script>

<style scoped>
.login-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    
}
.login-window {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 640px;
}
.logo {
    width: 10rem;
    height: 10rem;
}
</style>