/*
This file is part of SystemTestPortal.
Copyright (C) 2017  Institute of Software Technology, University of Stuttgart

SystemTestPortal 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 3 of the License, or
(at your option) any later version.

SystemTestPortal 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 SystemTestPortal.  If not, see <http://www.gnu.org/licenses/>.
*/

/**
 * Will toggle the button icon.
 * @param iTag - jQuery element of the icon
 * @param showUpArrow {boolean}
 */
function toggleExpandCollapseIcon(iTag, showUpArrow) {

    if (showUpArrow)
        iTag.removeClass("fa-angle-double-down").addClass("fa-angle-double-up");
    else
        iTag.removeClass("fa-angle-double-up").addClass("fa-angle-double-down")
}

/**
 * Will initialize a ExpandCollapseAllEnvironment (allowing multiple tabs to be opened simultaneously)
 * given the preconditions are met:
 *
 * * A accordion environment is set up
 * * Collapsible elements have the "panel-collapse" class
 * * Each of the single section collapse/expand buttons has the class specified by "collapseElementButtons".
 *
 * @param idToggleButton {string} - id of the expand/collapse all button
 * @param collapseElementButtons - class tag of a collapse/expand button of a single section
 */
function initExpandCollapseAll(idToggleButton, collapseElementButtons) {

    const toggleButton = $(`#${idToggleButton}`);
    const toggleIcon = toggleButton.find("i");

    toggleButton.on("click", function () {

        const anyCollapsed = $(".panel-collapse.collapse:not(.show)");

        if (anyCollapsed.length)
            $('.panel-collapse').removeData("bs.collapse")
                .collapse({parent: "", toggle: false})
                .collapse("show")
                .removeData("bs.collapse")
                .collapse({parent: "", toggle: false})
                .collapse("show");
        else
            $('.panel-collapse.show').collapse("hide");

    });


    const updateTopArrow = () => {
        const showUpArrow = !Boolean($(`.panel-collapse:not(.show)`).length);
        return toggleExpandCollapseIcon(toggleIcon, showUpArrow);
    };

    $(`.panel-collapse`)
        .on('hidden.bs.collapse', updateTopArrow)
        .on('shown.bs.collapse', updateTopArrow)
}

