const uploadSkin = async (event) => {
    event.preventDefault();
    const skinFile = document.getElementById("skinFile").files[0];

    if (!skinFile) {
        alert("Please, select a skin before uploading!");
        return;
    }

	let formData = new FormData();
	formData.append("file", skinFile);

    await fetch(`/api/uploadSkin`, {
        method: "POST",
        body: formData
    })

       window.location = window.location.href+'?eraseCache=true';
}

const uploadCape = async (event) => {
    event.preventDefault();
    const capeFile = document.getElementById("capeFile").files[0];

    if (!capeFile) {
        alert("Please, select a cape befora uploading!");
        return;
    }

	let formData = new FormData();
	formData.append("file", capeFile);

    await fetch(`/api/uploadCape`, {
        method: "POST",
        body: formData
    })

       window.location = window.location.href+'?eraseCache=true';
}


window.onload = async function() {
	document.getElementById("skinForm").addEventListener("submit", uploadSkin)
	if (document.getElementById("cape")) {
    	document.getElementById("cape").addEventListener("click", () => { set_cape_type("cape") }, false);
    	document.getElementById("cape").checked = true;

		document.getElementById("capeForm").addEventListener("submit", uploadCape);
	} 
	if (document.getElementById("elytra")) {
		document.getElementById("elytra").addEventListener("click", () => { set_cape_type("elytra") }, false );  
		document.getElementById("elytra").checked = false;
	}

	const username = await (await (fetch("/api/getUsername"))).text();

	let skinViewer = new skinview3d.SkinViewer({
	    canvas: document.getElementById("skin_container"),
	    width: 300,
	    height: 400,
	    skin: `https://launcher.foxarmy.org/skins/${username}.png`,
	    cape: `https://launcher.foxarmy.org/cloaks/${username}.png`
	});
	
	skinViewer.nameTag = username;
	skinViewer.loadPanorama("images/panorama.jpeg");
	skinViewer.fov = 120;
	skinViewer.zoom = 0.65;
	skinViewer.autoRotate = true;
	
	function set_cape_type(type) {
	    skinViewer.loadCape(`https://launcher.foxarmy.org/cloaks/${username}.png`, { backEquipment: type });
	}
	
	
}