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);

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

	if (response.status != 200) {
		alert(await response.text())
	} else {
		window.location.reload(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);

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

	if (response.status != 200) {
		alert(await response.text())
	} else {
		window.location.reload(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();
	const skinsUrl = (await (await fetch('/api/skinsUrl')).text()).replace('%username%', username);
	const capesUrl = (await (await fetch('/api/capesUrl')).text()).replace('%username%', username);

	let skinViewer = new skinview3d.SkinViewer({
	    canvas: document.getElementById("skin_container"),
	    width: 300,
	    height: 400,
	    skin: skinsUrl,
	    cape: capesUrl
	});
	
	
	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(capesUrl, { backEquipment: type });
	}
	
	
}