<script setup>

import VersionRender from '@/views/others/VersionRender.vue'
import ErrorMessage from '@/views/others/ErrorMessage.vue'

import { onMounted, ref } from 'vue';
import { GetUser } from '@/services/User'

import Api from '@/services/Api'
import url from '@/services/BackendURL'

import useEmitter from '@/services/Emitter';
const emitter = useEmitter();

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

function retrieveAvatar(){
    let userAvatarDisplay = document.getElementById("upload-image");
    Api().get('/user/retrieve-avatar?username=' + GetUser().username).then((response) => {
        console.log(response.data.image);

        userAvatarDisplay.src = url + "public/" + response.data.image;
    }).catch((err) => console.log("Internal error"));
}

onMounted(() => {
    let userAvatarDisplay = document.getElementById("upload-image");
    let sendAvatarForm = document.getElementById("send-avatar-form");
    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);

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

    userAvatarDisplay.addEventListener("click", (event) => {
        console.log("Clicked");
        sendAvatarFileUploader.click();
    })
});
</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">
            <img class="user-icon" src="img/def-avatar.jpg" id="upload-image">
            <div class="main-user-info">
                <b>{{ username }}</b><br>Miauler
            </div>
        </div>
    </div>
</template>


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

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

}

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

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

.user-icon {
    width: 40px;
    height: 40px;
}
</style>
