<script>
import { defineComponent } from 'vue'
import Sidebar from '@/components/Sidebar.vue'
import Cookies from 'js-cookie'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { config } from '@/main.js'

export default defineComponent({
    name: 'LoginView',
    setup() {
        const router = useRouter();
        // no this here
        if(Cookies.get("token") && Cookies.get("token").startsWith("HajeebToken")) return router.push("/profile/myself");
        return { router };
    },
    components: { Sidebar },
    methods: {
        async handleSubmit(e) {
            e.preventDefault();
            if(this.signedIn()) return this.router.push("/profile/myself");
            document.getElementById("submit").disabled = true;

            const formData = new FormData(e.target);
            let response = await axios.post(config.serverURL + "/account/token", {
                username: formData.get("username"),
                password: formData.get("password")
            })

            if(response.data.error) { // Login unsuccessful
                document.getElementById("submit").disabled = false;
                return alert(`Login error: ${response.data.message}`);
            }

            // Login successful
            Cookies.set("token", `HajeebToken ${response.data.token}`);
            return this.router.push("/profile/myself");
        },
        signedIn() {
            return Cookies.get("token") && Cookies.get("token").startsWith("HajeebToken");
        }
    }
})
</script>

<template>
    <div class="main">
        <Sidebar />
        <div class="login-container">
            <form class="login" id="form" @submit="handleSubmit">
                <img src="/assets/hajeebtok.png" width="300px" alt="HajeebTok logo"></img>
                <input type="text" placeholder="username" name="username" />
                <input type="password" placeholder="password" name="password" />
                <input type="submit" value="Log in/Sign up/Register/Enter Website" id="submit" />
            </form>
        </div>
    </div>
</template>

<style scoped>
.login-container {
    width: 100vw;
    height: 100vh;
    margin: 0;
    position: absolute;

    display: flex;
    justify-content: center;
    align-items: center;
    top: 0;
}

.login {
    background-color: var(--secondary-background-color);
    color: white;

    padding: 10px;
    border-radius: 5px;

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-self: center;
    gap: 10px;
}

input {
    font-family: "Knewave", system-ui;
    font-size: 30px;

    border: 2px solid var(--accent-color);
    border-radius: 5px;
}

input:focus {
    outline: none;
}
</style>
