<script setup>
import { onMounted, ref } from 'vue';
import { GetUser, LogoutUser } from '@/services/User'

import Server, { getBaseUrl } from '@/services/Server'

import { CreateWindow, CreateChildWindow, ClearWindow, GetFirstWindowId } from '../../services/Windows';
import Spinner from './Spinner.vue';
const loadedIcon = ref(false);

const username = ref("");
username.value = GetUser().username;

function retrieveAvatar(){
    let userAvatarDisplay = document.getElementById("upload-image");

    // Hide image + show spinner while loading
    loadedIcon.value = false;

    Server().get('/user/retrieve-avatar?username=' + GetUser().username)
    .then((response) => {
        if(response.data.image){
            const imgUrl = getBaseUrl() + "/public/" + response.data.image;

            // Wait for the image to fully load
            const img = new Image();
            img.src = imgUrl;

            img.onload = () => {
                userAvatarDisplay.src = imgUrl;
                loadedIcon.value = true;
            };

            img.onerror = () => {
                console.log("Image failed to load");
                loadedIcon.value = true; // fallback to avoid infinite spinner
            };
        }
    })
    .catch(() => console.log("Internal error"));
}

function LogOut(){
    LogoutUser();

    ClearWindow({type: "main_menu"});
    CreateWindow('login');
}

function EditSettings(){
    CreateChildWindow(GetFirstWindowId('main_menu'), 'settings', {
        user: GetUser()
    });
}

onMounted(() => {
    let userAvatarDisplay = document.getElementById("upload-image");
    let sendAvatarFileUploader = document.getElementById("send-avatar-file-uploader");
    
    sendAvatarFileUploader.addEventListener("change", (event) => {
        const formData = new FormData();
        const image = event.target.files[0];

        formData.append("image", image);

        Server().post('/user/upload-avatar', formData, {
            headers: { "Content-Type": "multipart/form-data" }
        }).then((response) => {
            retrieveAvatar();
        }).catch((err) => console.log("Internal error"));
    });

    userAvatarDisplay.addEventListener("click", (event) => {
        sendAvatarFileUploader.click();
    });

    retrieveAvatar();
});
</script>


<template>
    <form id="send-avatar-form" enctype="multipart/form-data">
        <input name="file" type="file" accept="image/*" id="send-avatar-file-uploader">
    </form>

    <div class="main-user-container">
        <div class="main-user-container-inner">
            <div class="user-icon-container">
                <img class="user-icon" src="/img/def-avatar.jpg" id="upload-image" draggable="false" v-show="loadedIcon">
                <Spinner v-show="!loadedIcon" :size="30"></Spinner>
            </div>
            <div class="main-user-info">
                <b>{{ username }}</b><br>
            </div>

            <div class="main-user-actions">
                <button class="btn-primary button-small sound-click" v-on:click.prevent="EditSettings">{{ $t("main-menu.settings") }}</button>
                <button class="btn-primary button-small sound-click" v-on:click.prevent="LogOut">{{ $t("main-menu.log-out") }}</button>
            </div>
        </div>
    </div>
</template>


<style scoped>
#send-avatar-form {
    display: none;
}

.button-small {
    padding: 10px;
}

.main-user-container {
    background-color: var(--color-background-softer);
    width: 100%;
    user-select: none;
}

.main-user-container-inner {
    padding: 10px;
    display: flex;
    align-items: center;

    justify-content: center;
}

.main-user-info {
    text-align: left;
    margin-left: 10px;
}

.user-icon {
    width: 40px;
    height: 40px;
}

.user-icon-container {
    width: 40px;
    height: 40px;
    overflow: hidden;
}

.main-user-actions {
    margin-left: auto;

    button {
        margin-left: 10px;
    }
}
</style>
