/*
	Files.js - Simple file save and load interface
	2020 by mercury0x0d, Creative Commons Attribution 4.0 International License
	Based on code by Tobias Amdahl (https://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip)

	Revision history:
	2020-05-24 - Initial release
*/



function FileDestroyClickedElement(event)
{
	/*
		Deletes the created A link element after the simulated click event causes it to be downloaded

		Input:
			event - The click event, handled by the browser

		Output:
			n/a
	*/


	document.body.removeChild(event.target);
}



function FileSave(filename, element)
{
	/*
		Saves data to a file

		Input:
			filename - A string containing the name for the file

		Output:
			n/a
	*/


	var textToSave = document.getElementById(element).value;
	var textToSaveAsBlob = new Blob([textToSave], {type:'text/plain'});
	var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
	var downloadLink = document.createElement('a');

	downloadLink.download = filename;
	downloadLink.innerHTML = 'Download File';
	downloadLink.href = textToSaveAsURL;
	downloadLink.onclick = FileDestroyClickedElement;
	downloadLink.style.display = 'none';
	document.body.appendChild(downloadLink);

	downloadLink.click();
}



function FileSaveElement(filenameElement, element)
{
	/*
		Saves data to a file

		Input:
			filenameElement - The element ID of the element containg the name for the file

		Output:
			n/a
	*/


	var textToSave = document.getElementById(element).value;
	var textToSaveAsBlob = new Blob([textToSave], {type:'text/plain'});
	var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
	var downloadLink = document.createElement('a');

	downloadLink.download = document.getElementById(filenameElement).value;
	downloadLink.innerHTML = 'Download File';
	downloadLink.href = textToSaveAsURL;
	downloadLink.onclick = FileDestroyClickedElement;
	downloadLink.style.display = 'none';

	document.body.appendChild(downloadLink);

	downloadLink.click();
}



function FileLoad(filenameElement, element)
{
	/*
		Saves data to a file

		Input:
			filenameElement - The element ID of the file selector element pointing to the file

		Output:
			n/a
	*/


	var fileToLoad = document.getElementById(filenameElement).files[0];
	var fileReader = new FileReader();

	fileReader.onload = function(fileLoadedEvent) 
	{
		var textFromFileLoaded = fileLoadedEvent.target.result;
		document.getElementById(element).value = textFromFileLoaded;
	};
	fileReader.readAsText(fileToLoad, 'UTF-8');
}
