/* global Bdf,$$,Resource,Overlay,Pane */

Resource.List = {};

Resource.List.init = function (callback) {
    Bdf.Ajax.loadResourceTree(function (resourceTree) {
        Resource.completeFolderArrays(resourceTree);
        let $treeBlock = $$("listpane_treeblock");
        $treeBlock.html(Bdf.render("resource:list/tree", resourceTree));
        Resource.List.initActions();
        Bdf.Deploy.init($treeBlock);
        if (callback) {
            callback();
        }
    });
};

Resource.List.initActions = function () {
    $$("listpane_button_newresource").click(Resource.Overlay.showCreationForm);
    $$("listpane_button_newapp").click(Resource.Overlay.showNewAppForm);
    var $body = $$("listpane_treeblock");
    _onClick("load-main", function () {
        if (!Bdf.confirmUnload()) {
            return false;
        }
        let reference = _getReferenceAncestor(this);
        Pane.loadOrDestock(reference.dataset.contentKey, function () {
            _loadContent(reference, false);
        });
        return false;
    });
    
    function _onClick(actionName, clickFunction) {
        $body.on("click", $$.toCssSelector({action: actionName}), clickFunction);
    }
    
    function _getReferenceAncestor(element) {
        return  Bdf.getMandatoryAncestor(element, {role: "content-reference"});
    }
    
    function _loadContent(reference, isInStock) {
        let path = reference.dataset.path;
        let linkType = reference.dataset.linkType;
        if (linkType === "text") {
            let overlayId = Bdf.Overlay.startRunning();
            Bdf.Ajax.loadStreamText(path, function (streamText) {
                Resource.Form.load(streamText, isInStock);
                Overlay.end(overlayId);
            });
        } else {
            Resource.Overlay.showResourceDisplay(linkType, path, reference.dataset.origins);
        }
        
    }

};

Resource.List.update = function (callback) {
    Bdf.Ajax.loadResourceTree(function (resourceTree) {
        var $tree = $$("listpane_treeblock").children($$.toCssSelector({role: "tree"}));
        Resource.completeFolderArrays(resourceTree);
        Resource.List.compareFolder($tree, resourceTree);
        Bdf.Deploy.init($tree);
        if (callback) {
            callback();
        }
    });
};

Resource.List.compareFolder = function ($list, newFolderObject) {
    var $currentSubfolders =  $list.children($$.toCssSelector({role: "folder"}));
    var $currentResources = $list.children($$.toCssSelector({role: "content-reference"}));
    var newSubfolderLength = newFolderObject.subfolderArray.length;
    if (newSubfolderLength === 0) {
        $currentSubfolders.remove();
    } else {
        let currentLength = $currentSubfolders.length;
        let p = 0;
        for(let i = 0; i < newSubfolderLength; i++) {
            let newSubfolder = newFolderObject.subfolderArray[i];
            let newName = newSubfolder.name;
            while(true) {
                if (p >= currentLength) {
                    _appendNewFolder(Bdf.render("resource:list/folder", newSubfolder));
                    break;
                } else {
                    let currentSubfolder = $currentSubfolders[p];
                    let currentName = currentSubfolder.dataset.name;
                    if (newName === currentName) {
                        _updateFolder(currentSubfolder, newSubfolder);
                        p++;
                        break;
                    } else if (newName < currentName) {
                        $(currentSubfolder).before(Bdf.render("resource:list/folder", newSubfolder));
                        break;
                    } else {
                        $(currentSubfolder).remove();
                        p++;
                    }
                }
            }
        }
        if (p < currentLength) {
            for(let i = p; i < currentLength; i++) {
                 $($currentSubfolders[i]).remove();
            }
        }
    }
    var newResourceLength = newFolderObject.resourceArray.length;
    if (newResourceLength === 0) {
        $currentResources.remove();
    } else {
        let currentLength = $currentResources.length;
        let p = 0;
        for(let i = 0; i < newResourceLength; i++) {
            let newResource = newFolderObject.resourceArray[i];
            let newName = newResource.name;
            while(true) {
                if (p >= currentLength) {
                    $list.append(Bdf.render("resource:list/resource", newResource));
                    break;
                } else {
                    let currentResource = $currentResources[p];
                    let currentName = currentResource.dataset.name;
                    if (newName === currentName) {
                        _updateResourceElement(currentResource, newResource);
                        p++;
                        break;
                    } else if (newName < currentName) {
                        $(currentResource).before(Bdf.render("resource:list/resource", newResource));
                        break;
                    } else {
                        $(currentResource).remove();
                        p++;
                    }
                }
            }
        }
        if (p < currentLength) {
            for(let i = p; i < currentLength; i++) {
                 $($currentResources[i]).remove();
            }
        }
    }
    
    
    function _appendNewFolder(html) {
        if ($currentResources.length > 0) {
            $($currentResources[0]).before(html);
        } else {
            $list.append(html);
        }
    }
    
    function _updateFolder(folderElement, folderObject) {
        let origins = Resource.originsToString(folderObject);
        let $folderTitle = $$(folderElement, {role: "folder-title", name: folderObject.name});
        $folderTitle.removeClass(function (index, className) {
            let result = /resource-origin-([a-zA-Z]+)/.exec(className);
            if (result) {
                return result[0];
            } else {
                return "";
            }
        });
        $folderTitle.addClass(Resource.getMatchingClass(origins));
        let $folderContent = $$(folderElement, {role: "folder-content", name: folderObject.name});
        Resource.List.compareFolder($folderContent, folderObject);
    };
    
    function _updateResourceElement(resourceElement, resourceObject) {
        let origins = Resource.originsToString(resourceObject);
        $(resourceElement).attr("data-origins", origins)
       .removeClass(function (index, className) {
            let result = /resource-origin-([a-zA-Z]+)/.exec(className);
            if (result) {
                return result[0];
            } else {
                return "";
            }
        }).addClass(Resource.getMatchingClass(origins));
    };
    
};