{% load static %}
{% load registry %}
{% load helpers %}
{% registry %}

<nav class="navbar navbar-default navbar-fixed-left navbar-inverse">
    <div class="container-fluid">
        <div class="navbar-header">
            <a class="navbar-brand" href="{% url 'home' %}">
                <img src="{% custom_branding_or_static 'logo' 'img/nautobot_logo.svg' %}" height="30" />
            </a>
        </div>

        <div id="navbar">
            {% if request.user.is_authenticated %}
                <form action="{% url 'search' %}" method="get" class="navbar-form" id="navbar_search" role="search">
                    <div class="input-group">
                        <input type="text" name="q" class="form-control" placeholder="Search {{ settings.BRANDING_TITLE }}">
                        <span class="input-group-btn">
                            <button type="submit" class="btn btn-primary">
                                <i class="mdi mdi-magnify"></i>
                            </button>
                        </span>
                    </div>
                </form>
            {% endif %}

            <ul class="nav navbar-nav">
                {% if request.user.is_authenticated %}
                    {% for tab_name, tab_details in registry.nav_menu.tabs.items %}
                        {% if request.user|has_one_or_more_perms:tab_details.permissions  %}
                            <li class="dropdown">
                                <a href="#dropdownMenu{{ forloop.counter }}" class="dropdown-toggle" data-tab-weight="{{ tab_details.weight }}" data-toggle="collapse" role="button" aria-haspopup="true" aria-expanded="false">
                                    <img src="{% custom_branding_or_static 'nav_bullet' 'img/nautobot_chevron.svg' %}" height="20px" />
                                    <span id="dropdown_title">{{ tab_name }}</span>
                                    <span class="mdi mdi-chevron-down"></span>
                                </a>
                                <ul class="collapse nav-dropdown-menu" id="dropdownMenu{{ forloop.counter }}">
                                    {% for group_name, group_details in tab_details.groups.items %}
                                        {% if request.user|has_one_or_more_perms:group_details.permissions  %}
                                            <li class="dropdown-header" data-group-weight="{{ group_details.weight }}">{{ group_name }}</li>
                                            {% for item_link, item_details in group_details.items.items %}
                                                {% if request.user|has_one_or_more_perms:item_details.permissions  %}
                                                    <li {% if not request.user|has_perms:item_details.permissions %} class="disabled"{% endif %}>
                                                        <a href="{{ item_link }}"
                                                            data-item-weight="{{ item_details.weight }}">
                                                            {{ item_details.name }}
                                                        </a>
                                                        {% if item_details.buttons.items|length > 0 %}
                                                            <div class="buttons">
                                                                {% for button_title, button_details in item_details.buttons.items %}
                                                                    {% if request.user|has_perms:button_details.permissions %}
                                                                        {% comment %}
                                                                            Use 'url xxx as variable' so that an invalid
                                                                            link doesn't throw a NoReverseMatch exception.
                                                                        {% endcomment %}
                                                                        {% url button_details.link as button_url %}
                                                                        {% if button_url %}
                                                                            <a href="{{ button_url }}"
                                                                               data-button-weight="{{ button_details.weight }}"
                                                                               class="btn btn-xs btn-{{ button_details.button_class }}"
                                                                               title="{{ button_title }}">
                                                                                <i class="mdi {{ button_details.icon_class }}"></i>
                                                                            </a>
                                                                        {% else %}
                                                                            <a class="btn btn-xs btn-danger"
                                                                               title="ERROR: Invalid link!">
                                                                                <i class="mdi mdi-alert"></i>
                                                                            </a>
                                                                        {% endif %}
                                                                    {% endif %}
                                                                {% endfor %}
                                                            </div>
                                                        {% endif %}
                                                    </li>
                                                {% endif %}
                                            {% endfor %}
                                            {% if not forloop.last %}
                                                <li class="divider"></li>
                                            {% endif %}
                                        {% endif %}
                                    {% endfor %}
                                </ul>
                            </li>
                        {% endif %}
                    {% endfor %}
                    <li class="nav-divider"></li>
                    <li class="dropdown">
                        <a href="#adminDropdown" class="dropdown-toggle" data-toggle="collapse" role="button"
                           aria-haspopup="true" aria-expanded="false">
                            <i class="mdi mdi-account"></i>
                            <span id="dropdown_title" title="{{ request.user }}">{{ request.user }}</span>
                            <span class="caret"></span>
                        </a>
                        <ul class="collapse nav-dropdown-menu" id="adminDropdown">
                            <li><a href="{% url 'user:profile' %}"><i class="mdi mdi-account-box"></i> Profile</a></li>
                            {% if request.user.is_staff %}
                                <li><a href="{% url 'admin:index' %}"><i class="mdi mdi-cogs"></i> Admin</a></li>
                            {% endif %}
                            <li class="divider"></li>
                            <li><a href="{% url 'logout' %}"><i class="mdi mdi-logout"></i> Log out</a></li>
                        </ul>
                    </li>
                {% else %}
                    <li>
                        <a href="{% url settings.LOGIN_URL %}?next={{ request.get_full_path | urlencode }}">
                            <i class="mdi mdi-login"></i> Log in
                        </a>
                    </li>
                {% endif %}
            </ul>
        </div>
    </div>
</nav>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        var navbar = document.querySelector('.navbar-fixed-left');
        var dropdownToggles = document.querySelectorAll('.navbar-fixed-left .navbar-nav > .dropdown > a[data-toggle="collapse"]');
        var dropdowns = document.querySelectorAll('.navbar-fixed-left .navbar-nav .collapse');
        var lastDropdownId = sessionStorage.getItem('lastOpenedDropdown');
        var savedScrollPosition = sessionStorage.getItem('navbarScrollPosition');
        var activeLink = sessionStorage.getItem('activeLink');

        // Function to reset stored dropdown state information
        function resetNavbarState() {
            sessionStorage.removeItem('lastOpenedDropdown');
            sessionStorage.removeItem('savedScrollPosition');
            sessionStorage.removeItem('activeLink');
        }

        // Select the navbar dropdown elements
        var navbarItems = document.querySelectorAll('.navbar-fixed-left .navbar-nav > .dropdown > .dropdown-toggle > #dropdown_title');

        // Add a title attribute and tooltip, only if necessary
        navbarItems.forEach(function(item) {
            // Check if the text overflows
            if (item.scrollWidth > item.clientWidth) {
                // Set the title attribute
                item.setAttribute('title', item.innerText);

                // Reinitialize Bootstrap tooltip
                $(item).tooltip();
            }
        });

        // Add an event listener for the home link click
        var homeLink = document.querySelector('.navbar-fixed-left .navbar-brand');
        if (homeLink) {
            homeLink.addEventListener('click', function() {
                resetNavbarState();
            });
        }

        // Debounce function
        function debounce(func, wait, immediate) {
            var timeout;
            return function() {
                var context = this, args = arguments;
                var later = function() {
                    timeout = null;
                    if (!immediate) func.apply(context, args);
                };
                var callNow = immediate && !timeout;
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
                if (callNow) func.apply(context, args);
            };
        }

        // Close all dropdowns except the one specified
        function closeAllDropdownsExcept(exceptId) {
            dropdowns.forEach(function(collapse) {
                if (collapse.id !== exceptId && collapse.classList.contains('in')) {
                    $(collapse).collapse('hide');
                }
            });
        }

        // Add click event listener to the dropdown links and save the clicked one
        function addLinkClickListeners() {
            var dropdownLinks = document.querySelectorAll('.navbar-fixed-left .navbar-nav > .dropdown > .nav-dropdown-menu > li > a');

            dropdownLinks.forEach(function(link) {
                link.addEventListener('click', function() {
                    sessionStorage.setItem('activeLink', link.getAttribute('href'));
                });
            });
        }

        // Close all dropdowns except the last opened one
        dropdownToggles.forEach(function(toggle) {
            toggle.addEventListener('click', function(event) {
                event.preventDefault();
                var collapseElement = document.getElementById(this.getAttribute('href').substring(1));

                if (!collapseElement.classList.contains('in')) {
                    closeAllDropdownsExcept(collapseElement.id);
                    $(collapseElement).collapse('show');
                    sessionStorage.setItem('lastOpenedDropdown', collapseElement.id);
                } else {
                    $(collapseElement).collapse('hide');
                    sessionStorage.removeItem('lastOpenedDropdown');
                }
            });
        });

        // Open the last opened dropdown
        if (lastDropdownId) {
            var lastDropdownMenu = document.getElementById(lastDropdownId);
            if (lastDropdownMenu && !lastDropdownMenu.classList.contains('in')) {
                $(lastDropdownMenu).collapse('show');
            }
        }

        // Restore the last saved scroll position
        if (savedScrollPosition) {
            navbar.scrollTop = savedScrollPosition;
        }

        // Save the scroll position when the navbar is scrolled
        navbar.addEventListener('scroll', debounce(function() {
            sessionStorage.setItem('navbarScrollPosition', navbar.scrollTop);
        }, 250));

         // Add click event listeners to dropdown links
        addLinkClickListeners();

        // Apply the 'active' class to the previously clicked link
        if (activeLink) {
            var previouslyClickedLink = document.querySelector('.navbar-fixed-left .navbar-nav > .dropdown > .nav-dropdown-menu > li > a[href="' + activeLink + '"]');
            var currentLocation = window.location.pathname + window.location.search;
            
            if (previouslyClickedLink && currentLocation.includes(previouslyClickedLink.getAttribute('href'))) {
                previouslyClickedLink.parentElement.classList.add('active');
            }
            else {
                sessionStorage.removeItem('activeLink');
            }
        }
    });
</script>
