{% load i18n %}

<div class="ml-4 mb-4">
    <input id="tree-search-input" class="form-control" type="text" placeholder="{% trans 'Search' %}"/>
</div>

<div id="tree-root">
    {% include 'konova/widgets/tree/checkbox/checkbox-tree-select-content.html' %}
</div>

<script>
    function toggleSelectedCssClass(element){
        element = $(element);
        var cssClass = "badge rlp-r"

        var directParent = element.closest(".tree-element-children")
        var root = element.parents(".tree-element-children")

        var otherCheckedInputsOfParent = directParent.find('.tree-input:checked');
        var otherCheckedInputsOfRoot = root.find('.tree-input:checked');

        if(otherCheckedInputsOfParent.length == 0){
            var parentLabel = directParent.siblings(".tree-label");
            parentLabel.removeClass(cssClass)
            if(otherCheckedInputsOfRoot.length == 0){
                var rootLabel = root.siblings(".tree-label")
                rootLabel.removeClass(cssClass)
            }
        }else{
            var rootAndParentLabel = root.siblings(".tree-label");
            rootAndParentLabel.addClass(cssClass);
        }

    }

    function changeHandler(event){
        toggleSelectedCssClass(this);
    }

    function searchInputHandler(event){
        var elem = $(this);
        var val = elem.val()
        var allTreeElements = $(".tree-element")
        var allTreeElementsContain = $(".tree-element").filter(function(){
            var reg = new RegExp(val, "i");
            return reg.test($(this).text());
            }
        );
        if(val.length > 0){
            // Hide everything
            allTreeElements.hide()
            // Now show again everything matching the query
            allTreeElementsContain.show()
        }else{
            // Show everything if no query exists
            allTreeElements.show()
        }
    }

    // Add event listener on search input
    $("#tree-search-input").keyup(searchInputHandler)

    // Add event listener on changed checkboxes
    $(".tree-input").change(changeHandler);

    // initialize all pre-checked checkboxes (e.g. on an edit form)
    var preCheckedElements = $(".tree-input:checked");
    preCheckedElements.each(function (index, element){
        toggleSelectedCssClass(element);
    })
</script>