// This file is part of Zoph.
//
// Zoph is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// Zoph is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Zoph; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
//
// This code is heavily based on
// https://www.sitepoint.com/html5-file-drag-and-drop/
// https://www.sitepoint.com/html5-javascript-open-dropped-files/
// https://www.sitepoint.com/html5-ajax-file-upload/
// https://www.sitepoint.com/html5-javascript-file-upload-progress-bar/
// by Craig Bugler


var zUpload=function() {

    function init() {
        if (window.File && window.FileList && window.FileReader) {
            let fileselect = document.getElementById("fileselect");
            let drop = document.getElementById("drop");
            fileselect.addEventListener("change", zUpload.handleFileSelect, false);
            drop.addEventListener("change", zUpload.handleFileSelect, false);


            // is XHR2 available?
            var xhr = new XMLHttpRequest();
            if (xhr.upload) {

                // file drop
                drop.addEventListener("dragover", zUpload.dragHover, false);
                drop.addEventListener("dragleave", zUpload.dragHover, false);
                drop.addEventListener("drop", zUpload.handleFileSelect, false);
                drop.style.display = "block";

                // remove submit button
                uploadSubmit.style.display = "none";
            }
        }
    }

    function dragHover(e) {
        e.stopPropagation();
        e.preventDefault();
        e.target.className = (e.type == "dragover" ? "hover" : "drop");
    }

    function handleFileSelect(e) {
        dragHover(e);
        let files=e.target.files || e.dataTransfer.files;
        for (let file of files) {
            doPreview(file);
            doUpload(file);
        }
    }

    function doPreview(file) {
        let results=document.getElementById("uploadResults");
        let msg =
            "<div id='upload-" + file.name + "' class='upload'>"+
            file.name + "<br />" +
            file.size + " bytes <br />" +
            "<progress id='progress-" + file.name + "' max='" + file.size + "'> 0% </progress>" +
            "</div>";
        results.innerHTML = msg + results.innerHTML;
    }

    function updateProgress(file, e) {
        let progress=document.getElementById('progress-' + file);
        let upload=document.getElementById('upload-' + file);
        let percent = Math.round((e.loaded / e.total * 100)).toString() + "%";

        progress.innerHTML=percent;
        progress.value = e.loaded;

        if (e.loaded == e.total) {
            upload.classList.add("completed");
            setTimeout(function(uploadId) {
                let delUpload=document.getElementById(uploadId);
                delUpload.parentNode.removeChild(delUpload);
            }, 4000, 'upload-' + file);
        }
    }

    function doUpload(file) {
        const filetypes = [
            "image/jpeg",
            "application/x-tar",
            "application/x-bzip2",
            "application/x-gzip",
            "application/zip",
            "application/gzip",
            "text/xml",
            "application/xml",
            "application/gpx+xml",
            "text/plain"
        ]
	    var xhr = new XMLHttpRequest();
	    if (xhr.upload && filetypes.includes(file.type)) {
            let formData = new FormData();
            formData.append("file", file, file.name);
            xhr.upload.addEventListener("progress", function(e) {
                zUpload.updateProgress(file.name, e);
            });
            // start upload
            xhr.open("POST", document.getElementById("upload").action, true);
            xhr.send(formData);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        var output = xhr.responseText;
                        if (output && output !== "") {
                            zImport.processDone(output);
                        }
                    }
                }
            };
        } else {
            let upload=document.getElementById('upload-' + file.name);
            upload.classList.add("uploadError");
            upload.innerHTML += "<span>Filetype not supported: " + file.type + "</span>";
            setTimeout(function(uploadId) {
                let delUpload=document.getElementById(uploadId);
                delUpload.parentNode.removeChild(delUpload);
            }, 30000, 'upload-' + file.name);
        }

    }

    return {
        init:init,
        dragHover:dragHover,
        handleFileSelect:handleFileSelect,
        updateProgress:updateProgress,
        doUpload:doUpload
    };
}();

if(window == top) {
    window.addEventListener("load",zUpload.init,false);
}
