{#
 # ---------------------------------------------------------------------
 #
 # GLPI - Gestionnaire Libre de Parc Informatique
 #
 # http://glpi-project.org
 #
 # @copyright 2015-2025 Teclib' and contributors.
 # @licence   https://www.gnu.org/licenses/gpl-3.0.html
 #
 # ---------------------------------------------------------------------
 #
 # LICENSE
 #
 # This file is part of GLPI.
 #
 # This program 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.
 #
 # This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.
 #
 # ---------------------------------------------------------------------
 #}

{% set rand = random() %}

<div class="dropdown dropstart">
    <button
        class="dropdown-item dropdown-toggle"
        type="button"
        data-bs-toggle="dropdown"
        aria-haspopup="true"
        aria-expanded="false"
        aria-label="{{ __("Change profile") }}"
    >
        <i class="ti ti-user-check"></i>
        {{ (session('glpiactiveprofile')['name'] ?? '') }}
    </button>
    <div class="dropdown-menu" data-bs-popper="none">
        <span class="dropdown-header">{{ __('Profiles') }}</span>
        {% for profile_id, profile in session('glpiprofiles') %}
            {% set is_active = profile_id == (session('glpiactiveprofile')['id'] ?? 0) %}
            <form action="{{ path('/Session/ChangeProfile') }}" method="POST">
                <button
                    class="dropdown-item {{ is_active ? 'active' : '' }}"
                    type="submit"
                >
                    <i class="ti ti-user-check"></i>
                    {{ profile['name'] }}
                </button>
                <input type="hidden" name="id" value="{{ profile_id }}" />
                <input type="hidden" name="_glpi_csrf_token" value="{{ csrf_token() }}" />
            </form>
        {% endfor %}
    </div>
</div>

{% set current_entity = session('glpiactive_entity_name') %}
{% set current_entity_short = session('glpiactive_entity_shortname') %}
{% if current_entity != current_entity_short %}
    {% set current_entity_short = '... > ' ~ current_entity_short %}
{% endif %}
{% if not is_multi_entities_mode() %}
    <span class="dropdown-item dropdown-item-text" title="{{ current_entity }}">
        <i class="ti ti-stack"></i>
        {{ current_entity_short|u.truncate(35, '...') }}
    </span>
{% else %}
    <div class="dropdown dropstart" id="entity-tree-dropdown-{{ rand }}">
        <a href="#" class="dropdown-item dropdown-toggle entity-dropdown-toggle" data-bs-toggle="dropdown" data-bs-auto-close="outside" title="{{ current_entity }}" aria-label="{{ __('Select the desired entity') }}">
            <i class="ti ti-stack"></i>
            {{ current_entity_short|u.truncate(35, '...') }}
        </a>
        <div class="dropdown-menu p-3 overflow-y-auto" style="max-height: calc(100vh - 8rem)">
            <h3>{{ __('Select the desired entity') }}</h3>

            <div class="alert alert-info" role="alert">
                {% set shortcut = __('Ctrl + Alt + E') %}
                {% if platform == constant("donatj\\UserAgent\\Platforms::MACINTOSH") %}
                    {% set shortcut = __('⌥ (option) + ⌘ (command) + E') %}
                {% endif %}
                {{ __("Tip: You can call this modal with %s keys combination")|format('<kbd>' ~ shortcut ~ '</kbd>')|raw }}
            </div>
            <div class="alert alert-info" role="alert">
                <i class="ti ti-info-circle-filled"></i>
                <span class="ms-2">
                {% set recursive_icon %}
                    <i class="ti ti-chevrons-down" title="{{ __('+ sub-entities') }}"></i>
                {% endset %}
                {{ __('Click on the %s icon to load the elements of the selected entity, as well as its sub-entities.')|format(recursive_icon)|raw }}
                </span>
            </div>

            {% set switch_to_full_structure_id = 'switch_to_full_structure_' ~ rand %}
            <form
                id="{{ switch_to_full_structure_id }}"
                method="POST"
                action="{{ path('/Session/ChangeEntity') }}"
            >
                <input type="hidden" name="full_structure" value="true">
                <input type="hidden" name="_glpi_csrf_token" value="{{ csrf_token() }}" />
            </form>

            <div class="input-group">
                <input type="text" class="form-control" name="entsearchtext" id="entsearchtext{{ rand }}"
                        placeholder="{{ __('Search entity') }}" autocomplete="off">
                <button id="entsearchsubmit{{ rand }}" type="submit" class="btn btn-icon btn-primary" title="{{ __('Search') }}"
                        data-bs-toggle="tooltip" data-bs-placement="top">
                    <i class="ti ti-search"></i>
                </button>
                <a class="btn btn-icon btn-outline-secondary" href="#" id="entsearchtext{{ rand }}_clear"
                    title="{{ __("Clear search") }}" data-bs-toggle="tooltip" data-bs-placement="top">
                        <i class="ti ti-x"></i>
                </a>
                <button
                    class="btn btn-secondary"
                    title="{{ __('Select all') }}"
                    data-bs-toggle="tooltip"
                    data-bs-placement="top"
                    form="{{ switch_to_full_structure_id }}"
                    type="submit"
                >
                    <i class="ti ti-eye"></i>
                </button>
            </div>

            <div class="fancytree-grid-container flexbox-item-grow entity_tree overflow-x-auto">
                <table id="tree_entity{{ rand }}" aria-label="{{ __('Entity tree') }}">
                <colgroup>
                    <col></col>
                </colgroup>
                <thead>
                    <tr>
                        <th class="parent-path"></th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
                </table>
                <div id="verticalScrollbar-{{ rand }}" class="position-absolute overflow-auto" style="height:100%; width: 16px; top: 0; right: 0;">
                    <div class="fake-scrollbar-inner" style="height: 100%; width: 100%;">
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
    $(function() {
        let block_fake_scrollbar_event = false;
        var initTree{{ rand }} = function() {
            if ($.ui.fancytree.getTree("#tree_entity{{ rand }}") !== null) {
                return;
            }

            $('#tree_entity{{ rand }}').fancytree({
                // load plugins
                extensions: ['filter', 'glyph', 'grid'],

                // Scroll node into visible area, when focused by keyboard
                autoScroll: true,

                // enable font-awesome icons
                glyph: {
                    preset: "awesome5",
                    map: {}
                },

                // enable virtual dom, it requires the grid (table extension) plugin
                table: {
                    indentation: 20,       // indent 20px per node level
                    nodeColumnIdx: 0,      // render the node title into the 1st column
                    mergeStatusColumns: false,
                },
                grid: {
                    mergeStatusColumns: false,
                },
                viewport: {
                    enabled: true,
                    count: 15, // number of items to display at once
                },

                // translate strings
                strings: {
                    loading: __("Loading..."),
                    loadError: __("Unexpected error."),
                    moreData: __("More..."),
                    noData: __("No entity found")
                },

                // load data by ajax
                source: {
                    url:  '{{ path("/ajax/entitytreesons.php") }}',
                    cache: false
                },

                // filter plugin options
                filter: {
                    mode: "hide", // remove unmatched nodes
                    autoExpand: true, // if results found in children, auto-expand parent
                    nodata: '{{ __("No entity found") }}', // message when no data found
                    highlight: false, // do not highlight matches by wrapping inside tags (when true, this strip the a tag)
                    counter: false, // do not show counters when filtering entity tree
                },

                // update scrollbar when viewport is updated
                updateViewport: function(event, data) {
                    const fake_scrollbar = $("#verticalScrollbar-{{ rand }}");
                    const item_height = $(data.tree.tbody).find('tr').height();
                    block_fake_scrollbar_event = true;
                    fake_scrollbar.find('.fake-scrollbar-inner').height(item_height * data.tree.visibleNodeList.length);
                    fake_scrollbar.scrollTop(item_height * data.tree.viewport.start);

                    initTooltips();
                },

                // update toolips on node expand
                expand: function(event, data) {
                    initTooltips();
                },
            });
        };

        //Sync viewport with fake scrollbar
        $("#verticalScrollbar-{{ rand }}").on('scroll', function(e) {
            if (block_fake_scrollbar_event) {
                block_fake_scrollbar_event = false;
                return;
            }
            const fake_scrollbar = $(e.target);
            const item_height = fake_scrollbar.find('.fake-scrollbar-inner').height() / $.ui.fancytree.getTree("#tree_entity{{ rand }}").visibleNodeList.length;
            const new_start = Math.round(fake_scrollbar.scrollTop() / item_height);
            $.ui.fancytree.getTree("#tree_entity{{ rand }}").setViewport({
                start: new_start,
            });
        });

      // init Entities tree only when user ask for it (when dropdown is opened)
        document.getElementById('entity-tree-dropdown-{{ rand }}')
            .addEventListener('show.bs.dropdown', function (event) {
                initTree{{ rand }}();
            });

        var searchTree = function() {
            var search_text = $("#entsearchtext{{ rand }}").val();
            $.ui.fancytree.getTree("#tree_entity{{ rand }}").filterBranches(search_text);
        }

        $('#entsearchsubmit{{ rand }}').click(function(event) {
            // cancel submit of entity search form
            event.preventDefault();

            searchTree();
        });

        $('#entsearchtext{{ rand }}').keyup(function () {
            var inputsearch = $(this);
            typewatch(function () {
                if (inputsearch.val().length >= 3) {
                searchTree();
                }
            }, 500);
        }).focus();

        $('#entsearchtext{{ rand }}_clear').click(function () {
            $('#entsearchtext{{ rand }}').val('');
            searchTree();
        });

        // when the shortcut for entity form is called
        hotkeys('ctrl+alt+e, option+command+e', async function(e) {
            e.stopPropagation();
            e.preventDefault();
            $('.user-menu-dropdown-toggle:visible').dropdown('show');
            await new Promise(r => setTimeout(r, 100));
            $('.user-menu-dropdown-toggle:visible').parent().find('.entity-dropdown-toggle').dropdown('show');
            $('input[name=entsearchtext]').filter(":visible")[0].focus();
        });
    });
    </script>
{% endif %}
