
String.prototype.hashCode = function () {
    var hash = 0,
            i, chr;
    if (this.length === 0)
        return hash;
    for (i = 0; i < this.length; i++) {
        chr = this.charCodeAt(i);
        hash = ((hash << 5) - hash) + chr;
        hash |= 0;
    }
    return hash;
};

let globalItems = {};
var dropArea = document.querySelector("#dropArea");
dropArea.addEventListener(
        "dragover",
        function (e) {
            e = e || event;
            e.preventDefault();
        },
        false
        );
dropArea.addEventListener(
        "drop",
        function (event) {
            event.preventDefault();
            var items = event.dataTransfer.items;
            //console.log(event.dataTransfer.files);
            window.globalItems = items;
            console.log(window.globalItems);

            if (HasTree) {
                var res = confirm("Das Projekt hat bereits einen Dokumentenbaum. Möchten Sie den Baum überschreiben?");
            } else {
                var res = true;
            }
            if (res) {
                newSubTreeNodePath = '';
                    $("#UploadModal").modal('show');
                console.log("UploadModal show " + window.globalItems);
                    getFilesDataTransferItems(window.globalItems).then(files => {
                        // console.log("OUTPUT FILES:", filesToUpload);
                             $.post("index.php?module=project&event=removeDocumentStructureJSON&ProjectID=" + ProjectID, {}, function () {
                        UploadChain(0);
                                 var rawOutput = JSON.stringify(files);
                                 /*
                                output = rawOutput
                                .substring(1, rawOutput.length - 1)
                                .replace(/},/g, "}<br/>")
                                .replace(/\[/g, "[<div class='folder'>")
                                .replace(/\]/g, "]</div>");
                                 console.log(rawOutput);
                                 console.log(output);
                                 */
                        uploadTree(rawOutput);
                          });
                        
                        // document.querySelector("#output").innerHTML = output;
                    });
              




            }
        },
        false
        );





/*
SubTree-Upload 
*/


var dropAreaSubTree = document.querySelector("#dropAreaSubTree");
dropAreaSubTree.addEventListener(
    "dragover",
    function (e) {
        e = e || event;
        e.preventDefault();
    },
    false
);
dropAreaSubTree.addEventListener(
    "drop",
    function (event) {
        event.preventDefault();
        var items = event.dataTransfer.items;
        //console.log(event.dataTransfer.files);
        window.globalItems = items;
        console.log('dropAreaSubTree: ' + window.globalItems);

        if (HasTree) {
            var res = confirm("Baum an dieser Stelle (" + newSubTreeNodePath  + ") hochladen?");
        } else {
            var res = true;
        }
        if (res) {


            $("#UploadModal").modal('show');
            $("#UploadFileTreeModal").modal('hide');
            console.log("UploadModal show " + window.globalItems);
            getFilesDataTransferItems(window.globalItems).then(files => {
                console.log("OUTPUT FILES:", filesToUpload);
                UploadChain(0);                
                AppendAndUploadTree(files);                   
            });
        }
    },
    false
);

/**
 * 
 */
function UploadChain(indexNum) {
    let item = filesToUpload[indexNum];
    console.log("Item to be uploaded: ", item);
    overrideFiles = 1; //Erstmal immer überschreiben / neu anlegen
    ItemPath = item.path;
    if (newSubTreeNodePath != '') {
        ItemPath = '/' + newSubTreeNodePath + item.path;
        overrideFiles = $('#overrideFiles').is(':checked') ? 1 : 0; //Wenn neuer Sub-Baum hochgeladen wird, auf die Checkbox achten
    } 

    uploadFile(item.file, ItemPath, overrideFiles).then((res) => {
        if (indexNum < filesToUpload.length - 1) {
            console.log("End. Continue to next call.");
            var percentage = Math.round((indexNum / filesToUpload.length) * 100);
            $("#" + IdForTreeProgress).css('width', percentage + '%');
            $("#" + IdForTreeProgress).html(percentage + "% - " + indexNum + ' / ' + filesToUpload.length);
            UploadChain(indexNum + 1);
        } else {
            $("#" + IdForTreeProgress).html(filesToUpload.length + ' / ' + filesToUpload.length);
            $("#" + IdForTreeProgress).css('width', '100%');
           // $("#FileBar_" + FileName).removeClass('progress-bar-info');
           // $("#FileBar_" + FileName).addClass('progress-bar-success');
        }
    });

}

/**
 * 
 */
function doInterval(item) {
    setInterval(function () {
        console.log(item)
    }, 2000);
}

var IdForTreeProgress = '';
function uploadTree(JSON) {

    var FileName = "DocTreeStructure";
    $("#FileFound").show();
    $("#ProgressSection").show();

    var url = 'index.php?module=project&event=uploadDocumentStructure&ProjectID=' + ProjectID;
    var xhr = new XMLHttpRequest();
    var formData = new FormData()
    xhr.open('POST', url, true);
    IdForTreeProgress = 'FileBar_' + FileName;
    $("#ProgressSection").append('<h6><b>Dokumentenbaum</b> wird hochgeladen</h6><div class="progress"><div class="progress-bar progress-bar-info" id="FileBar_' + FileName + '" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width:0%"></div></div>');
    xhr.addEventListener('readystatechange', function (e) {
        if (xhr.readyState === 4 && xhr.status === 200) {
            $("#FileBar_" + FileName).css('width', '100%');
            $("#CloseUpload").show();
            $("#SuccessAlert").show();
            // Done. Inform the user
        } else if (xhr.readyState === 4 && xhr.status !== 200) {
            // Error. Inform the user
            $("#FileBar_" + FileName).removeClass('progress-bar-info');
            $("#FileBar_" + FileName).addClass('progress-bar-danger');
        }
    });

    xhr.onprogress = function (pe) {
        if (pe.lengthComputable) {
            var percentage = Math.round((pe.loaded / pe.total) * 100);
            $("#FileBar_" + FileName).css('width', percentage + '%');
        }
    };

    formData.append('json', JSON);
    xhr.send(formData);
}

function AppendAndUploadTree(JSON) {

    var FileName = "DocTreeStructure";
    $("#FileFound").show();
    $("#ProgressSection").show();

    var url = 'index.php?module=project&event=storeJSON&ProjectID=' + ProjectID;
    var xhr = new XMLHttpRequest();
    var formData = new FormData()
    xhr.open('POST', url, true);
    IdForTreeProgress = 'FileBar_' + FileName;
    $("#ProgressSection").append('<h6><b>Dokumentenbaum</b> wird hochgeladen</h6><div class="progress"><div class="progress-bar progress-bar-info" id="FileBar_' + FileName + '" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width:0%"></div></div>');
    xhr.addEventListener('readystatechange', function (e) {
        if (xhr.readyState === 4 && xhr.status === 200) {
            $("#FileBar_" + FileName).css('width', '100%');
            $("#CloseUpload").show();
            $("#SuccessAlert").show();
            // Done. Inform the user
        } else if (xhr.readyState === 4 && xhr.status !== 200) {
            // Error. Inform the user
            $("#FileBar_" + FileName).removeClass('progress-bar-info');
            $("#FileBar_" + FileName).addClass('progress-bar-danger');
        }
    });

    xhr.onprogress = function (pe) {
        if (pe.lengthComputable) {
            var percentage = Math.round((pe.loaded / pe.total) * 100);
            $("#FileBar_" + FileName).css('width', percentage + '%');
        }
    };

    const treeInstance = $("#DocTree").jstree(true); //Bestehnder Baum

    var newSubTreeData = createJSTree(JSON);
    
    if (newSubTreeData.length > 0) {
        const newSubTreeRoot = newSubTreeData[0]; // Wurzel des neuen SubTrees
        addSubTreeRecursively(treeInstance, SubTreeParentNodeID, newSubTreeRoot);
    } else {
        console.error('Der neue SubTree enthält keine Daten.');
    }
/*
    if (MySubTree.length > 0) {
        treeInstance.create_node(SubTreeParentNodeID, MySubTree[0], 'last', function (newNode) {
            console.log('Neuer SubTree hinzugefügt:', newNode);
        });
    } else {
        console.error('Der neue SubTree enthält keine Daten.');
    }
*/
    newJSON = JSON.stringify(treeInstance.get_json('#', { flat: false }));

    formData.append('json', newJSON);
    xhr.send(formData);
}

function createJSTree(docStructure) {
    const jsTree = [];

    docStructure.forEach(directory => {
        const elem = {};
        let isFile = false;

        if (!Array.isArray(directory) && typeof directory === 'string') {
            // Es handelt sich um eine Datei
            isFile = true;
            const fileName = directory.replace('(File)', '').trim();

            elem.text = fileName;
            elem.icon = "jstree-file";
            elem.changedname = null; 
            elem.hmtype = "file";
        } else {
            // Es handelt sich um einen Ordner
            const name = directory.name;
            elem.text = name;
            elem.hmtype = "folder";

            if (directory.subfolder && directory.subfolder.length > 0) {
                elem.children = createJSTree(directory.subfolder);
            }
        }

        jsTree.push(elem);
    });

    return jsTree;
}


// Funktion, um einen Knoten mit einem bestimmten Namen unter einem Elternknoten zu finden
function findNodeByName(treeInstance, parentNodeId, nodeName) {
    const children = treeInstance.get_node(parentNodeId).children;
    for (const childId of children) {
        const childNode = treeInstance.get_node(childId);
        if (childNode.text === nodeName) {
            return childNode;
        }
    }
    return null;
}

// Funktion, um einen neuen SubTree rekursiv in den bestehenden Baum einzufügen
function addSubTreeRecursively(treeInstance, parentNodeId, newSubTreeNode) {
    const existingNode = findNodeByName(treeInstance, parentNodeId, newSubTreeNode.text);

    if (existingNode) {
        console.log(`Knoten "${newSubTreeNode.text}" existiert bereits. Ergänze Inhalte.`);
        // Wenn der Knoten existiert, füge seine Kinder rekursiv hinzu
        if (newSubTreeNode.children && newSubTreeNode.children.length > 0) {
            newSubTreeNode.children.forEach((child) => {
                addSubTreeRecursively(treeInstance, existingNode.id, child);
            });
        }
    } else {
        console.log(`Knoten "${newSubTreeNode.text}" existiert nicht. Füge neuen Knoten hinzu.`);
        // Wenn der Knoten nicht existiert, füge ihn hinzu
        treeInstance.create_node(parentNodeId, newSubTreeNode, 'last');
    }
}

/**
 * Die Datei in index.php?module=upload hochladen
 */
function uploadFile(file, filePath, overrideFiles) {
    return new Promise(resolve => {
        var FileName = (filePath + file.name).hashCode();
        $("#FileFound").show();
        $("#ProgressSection").show();

        var url = 'index.php?module=upload&isTreeUpload=1';
        var xhr = new XMLHttpRequest();
        var formData = new FormData()
        xhr.open('POST', url, true);
        $("#ProgressSection").append('<div id="ProgressSectionItem_' + FileName + '"><h6><b>' + file.name + '</b> wird hochgeladen</h6><div class="progress"><div class="progress-bar progress-bar-info" id="FileBar_' + FileName + '" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width:0%"></div></div><p id="StatusError_' + FileName + '" style="color:red;"></p><p style="color:red;" id="ErrorNotice_' + FileName + '"></p></div>');
        xhr.addEventListener('readystatechange', function (e) {
            if (xhr.readyState === 4 && xhr.status === 200) {
                $("#FileBar_" + FileName).css('width', '100%');

                $("#ProgressSectionItem_" + FileName).fadeOut();
                resolve(1);
                // Done. Inform the user
            } else if (xhr.readyState === 4 && xhr.status !== 200) {
                console.log("Error!");
                $("#FileBar_" + FileName).removeClass('progress-bar-info');
                $("#FileBar_" + FileName).addClass('progress-bar-danger');
                $("#FileBar_" + FileName).css('width', '100%');
                $("#StatusError_" + FileName).html('<b>HTTP Fehler: ' + xhr.statusText + '</b>');
                $("#ErrorNotice_" + FileName).html('Es ist ein Fehler aufgetreten. Bitte überprüfen Sie die Serverkonfiguration und laden Sie die Datei oder den gesamten Baum erneut hoch.');
                resolve(0);
            }
        })

        xhr.onprogress = function (pe) {
            if (pe.lengthComputable) {
                var percentage = Math.round((pe.loaded / pe.total) * 100);
                $("#FileBar_" + FileName).css('width', percentage + '%');
            }
        }
        formData.append('overrideFiles', overrideFiles);
        formData.append('UploadFile', file);
        formData.append('ProjectID', ProjectID);
        formData.append('FilePathFolder', filePath);
        formData.append('ShortDescr', 'Project_' + ProjectID + '_' + CryptoJS.enc.Hex.stringify(CryptoJS.SHA1(filePath)));
        xhr.send(formData);
    });
}

var filesToUpload = [];

function getFilesDataTransferItems(dataTransferItems) {
    function traverseFileTreePromise(item, path = "", folder) {
        return new Promise(resolve => {
            if (item.isFile) {
                // console.log("Is File");
                item.file(file => {
                    file.filepath = path || "" + file.name; //save full path
                    // console.log("Here is a file: ", file);
                    // console.log("Here is the full path : ", item.fullPath);
                    folder.push("(File)" + file.name);
                    //  console.log("Folder of file: ", folder);
                    //uploadFile(file, item.fullPath);
                    filesToUpload.push({file: file, path: item.fullPath});
                    // console.log(filesToUpload);
                    resolve(file);
                });
            } else if (item.isDirectory) {
                //console.log("Is Directory");
                //  console.log(item.file);
                let dirReader = item.createReader();
                dirReader.readEntries(entries => {
                    let entriesPromises = [];
                    subfolder = [];
                    folder.push({name: item.name, subfolder: subfolder});
                    for (let entr of entries)
                        entriesPromises.push(
                                traverseFileTreePromise(entr, path || "" + item.name + "/", subfolder)
                                );
                    resolve(Promise.all(entriesPromises));
                });
            }
        });
    }

    let files = [];
    return new Promise((resolve, reject) => {
        let entriesPromises = [];
        for (let it of dataTransferItems)
            entriesPromises.push(
                    traverseFileTreePromise(it.webkitGetAsEntry(), null, files)
                    );
        Promise.all(entriesPromises).then(entries => {
            resolve(files);
        });
    });
}


function addFiles(e) {
    e.stopPropagation();
    e.preventDefault();

    // if directory support is available
    if (e.dataTransfer && e.dataTransfer.items)
    {
        var items = e.dataTransfer.items;
        for (var i = 0; i < items.length; i++) {
            var item = items[i].webkitGetAsEntry();

            if (item) {
                addDirectory(item);
            }
        }
        return;
    }

    // Fallback
    var files = e.target.files || e.dataTransfer.files;
    if (!files.length)
    {
        alert('Datei ist nicht erlaubt!');
        return;
    }

    processFile(files);
}

function addDirectory(item) {
    var _this = this;
    if (item.isDirectory) {
        var directoryReader = item.createReader();
        directoryReader.readEntries(function (entries) {
            entries.forEach(function (entry) {
                _this.addDirectory(entry);
            });
        });
    } else {
        item.file(function (file) {
            processFile([file], 0);
        });
    }
}
