const htmlElement = document.documentElement,
    body = document.body,
    sidebar = $('.sidebar'),
    alignLeft = `<svg xmlns="http://www.w3.org/2000/svg" 
                      width="24" 
                      height="24" 
                      viewBox="0 0 24 24" 
                      fill="none" 
                      stroke="currentColor" 
                      stroke-width="2" 
                      stroke-linecap="round" 
                      stroke-linejoin="round" 
                      class="feather feather-align-left">
                    <line x1="17" y1="10" x2="3" y2="10"></line>
                    <line x1="21" y1="6" x2="3" y2="6"></line>
                    <line x1="21" y1="14" x2="3" y2="14"></line>
                    <line x1="17" y1="18" x2="3" y2="18"></line>
                 </svg>`,
    alignCenter = `<svg xmlns="http://www.w3.org/2000/svg" 
                        width="24" 
                        height="24" 
                        viewBox="0 0 24 24" 
                        fill="none" 
                        stroke="currentColor" 
                        stroke-width="2" 
                        stroke-linecap="round" 
                        stroke-linejoin="round" 
                        class="feather feather-align-center">
                       <line x1="18" y1="10" x2="6" y2="10"></line>
                       <line x1="21" y1="6" x2="3" y2="6"></line>
                       <line x1="21" y1="14" x2="3" y2="14"></line>
                       <line x1="18" y1="18" x2="6" y2="18"></line>
                   </svg>`,
    alignJustify = `<svg xmlns="http://www.w3.org/2000/svg" 
                         width="24" 
                         height="24" 
                         viewBox="0 0 24 24" 
                         fill="none" 
                         stroke="currentColor" 
                         stroke-width="2" 
                         stroke-linecap="round" 
                         stroke-linejoin="round" 
                         class="feather feather-align-justify">
                        <line x1="21" y1="10" x2="3" y2="10"></line>
                        <line x1="21" y1="6" x2="3" y2="6"></line>
                        <line x1="21" y1="14" x2="3" y2="14"></line>
                        <line x1="21" y1="18" x2="3" y2="18"></line>
                    </svg>`,
    sun = `<svg xmlns="http://www.w3.org/2000/svg" 
                width="24" 
                height="24" 
                viewBox="0 0 24 24" 
                fill="none" 
                stroke="currentColor" 
                stroke-width="2" 
                stroke-linecap="round" 
                stroke-linejoin="round" 
                class="feather feather-sun">
                <circle cx="12" cy="12" r="5"></circle>
                <line x1="12" y1="1" x2="12" y2="3"></line>
                <line x1="12" y1="21" x2="12" y2="23"></line>
                <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
                <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
                <line x1="1" y1="12" x2="3" y2="12"></line>
                <line x1="21" y1="12" x2="23" y2="12"></line>
                <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
                <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
           </svg>`,
    moon = `<svg xmlns="http://www.w3.org/2000/svg" 
                 width="24" 
                 height="24" 
                 viewBox="0 0 24 24" 
                 fill="none" 
                 stroke="currentColor" 
                 stroke-width="2" 
                 stroke-linecap="round" 
                 stroke-linejoin="round" 
                 class="feather feather-moon">
                <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
            </svg>`,
    maximize = `<svg xmlns="http://www.w3.org/2000/svg" 
                     width="24" 
                     height="24" 
                     viewBox="0 0 24 24" 
                     fill="none" 
                     stroke="currentColor" 
                     stroke-width="2" 
                     stroke-linecap="round" 
                     stroke-linejoin="round" 
                     class="feather feather-maximize">
                    <path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"></path>
                </svg>`,
    minimize = `<svg xmlns="http://www.w3.org/2000/svg" 
                     width="24" 
                     height="24" 
                     viewBox="0 0 24 24" 
                     fill="none" 
                     stroke="currentColor" 
                     stroke-width="2" 
                     stroke-linecap="round" 
                     stroke-linejoin="round" 
                     class="feather feather-minimize">
                    <path d="M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"></path>
                </svg>`,
    toggleSidebarBtn = document.getElementById('toggleSidebar'),
    toggleThemeBtn = document.getElementById('toggleTheme'),
    toggleFullscreenBtn = document.getElementById('toggleFullscreen'),
    toggleMobileMenuBtn = document.getElementById('toggleMobileMenu');

let xAxisColor = '#2f3541',
    yAxisColor = '#2f3541';


// Some Utility Function

const addClass = (element, className) => {
    element.classList.add(className);
}
const removeClass = (element, className) => {
    element.classList.remove(className);
}
const toggleClass = (element, className) => {
    element.classList.toggle(className)
}


// Add active class to nav-link based on dynamic url
let current = location.pathname.split('/').pop();
$('.nav li a', sidebar).each(function () {
    let $this = $(this);
    addActiveClass($this);
});

// For active classes of sidebar menu
function addActiveClass(element) {
    if (element.attr('href').includes(current ? current : 'index.html')) {
        element.parents('.nav-item').last().addClass('active');
        if (element.parents('.sub-menu').length) {
            element.closest('.collapse').addClass('show');
            element.addClass('active');
        }
        if (element.parents('.submenu-item').length) {
            element.addClass('active');
        }
    }
}

// Check and Set Active Sidebar
(function () {
    let sidebarType = localStorage.getItem('sidebarType');

    if (toggleSidebarBtn) {
        if (sidebarType === 'hoverOnly') {
            addClass(body, 'sidebar-hover-only')
            toggleSidebarBtn.innerHTML = alignJustify;
            sidebar.find('.collapse.show').collapse('hide');
        } else if (sidebarType === 'iconOnly') {
            addClass(body, 'sidebar-icon-only')
            toggleSidebarBtn.innerHTML = alignCenter;
        } else {
            toggleSidebarBtn.innerHTML = alignLeft;
        }
    }
}());

// Check and Set Active Theme
const toggleTheme = () => {
    let theme = localStorage.getItem('theme');

    if (theme === 'dark') {
        htmlElement.setAttribute('theme', 'dark');
        if(toggleThemeBtn) toggleThemeBtn.innerHTML = sun;

        // Render chart
        xAxisColor = '#2f3541'
        yAxisColor = '#2f3541'
    } else {
        htmlElement.setAttribute('theme', 'light');
        if(toggleThemeBtn) toggleThemeBtn.innerHTML = moon;

        // Render chart
        xAxisColor = '#F0F2F5'
        yAxisColor = '#F0F2F5'
    }
    if (typeof renderCharts === 'function')
        renderCharts();
    if (typeof renderChartistChart === 'function')
        renderChartistChart();
}
// Initialize theme
toggleTheme();

// Check and Set Active Layout
const toggleLayout = () => {
    let layout = localStorage.getItem('layout');
    htmlElement.setAttribute('dir', layout ? layout : 'ltr');
};
// Initialize Layout
toggleLayout();

// Active class add in layout switching
const activeClassAddInSwitchDrawer = () => {
    let themeType = localStorage.getItem('theme'),
        layoutType = localStorage.getItem('layout'),
        sidebarType = localStorage.getItem('sidebarType');

    document.querySelectorAll('.switch-template-theme').forEach(item => {
        if (item.dataset['value'] === themeType) addClass(item, 'active');
        else removeClass(item, 'active');
    })
    document.querySelectorAll('.switch-template-layout').forEach(item => {
        if (item.dataset['value'] === layoutType) addClass(item, 'active');
        else removeClass(item, 'active');
    })
    document.querySelectorAll('.switch-template-sidebar').forEach(item => {
        if (item.dataset['value'] === sidebarType) addClass(item, 'active');
        else removeClass(item, 'active');
    })
}

// Image uploader
const initImageUpload = () => {
    let customFileUploader = document.getElementsByClassName('custom-file-uploader');
    for (let i = 0; i < customFileUploader.length; i++) {
        let input = customFileUploader[i].getElementsByTagName('input')[0],
            imgElement = customFileUploader[i].getElementsByTagName('img')[0];
        input.addEventListener('change', () => {
            let path = URL.createObjectURL(document.getElementById(input.id).files[0]);
            if (path) imgElement.src = path
        })
    }
}

$(function () {
    "use strict";

    // Initialize Global Search Function
    if(typeof initGlobalSearch === 'function') initGlobalSearch();

    // Initialize Bootstrap Tooltip
    $('[data-toggle="tooltip"]').tooltip();

    // Initialize Tippyjs
    tippy('[data-tippy-content]');

    // Initialize image uploader
    initImageUpload();

    // Initialize Feather Icon
    if (typeof feather === 'undefined') console.log('Required Feather icon!!')
    else feather.replace();

    // Toggle Mobile Menu
    if(toggleMobileMenuBtn) {
        toggleMobileMenuBtn.onclick = (e) => {
            toggleClass(document.querySelector('.sidebar-offcanvas'), 'active')
        }
    }

    // Toggle Template Setting Sidebar
    [
        document.querySelector('#toggleSidebarTemplateSetting'),
        document.querySelector('.close-sidebar'),
        document.querySelector('.template-setting-sidebar-overlay')
    ].forEach(item => {
        if (item) {
            item.onclick = () => {
                toggleClass(document.querySelector('.sidebar-template-setting'), 'active');
                toggleClass(document.querySelector('.template-setting-sidebar-overlay'), 'open-overlay');
            }
        }
    });

    // Toggle Fullscreen
    if (toggleFullscreenBtn) {
        toggleFullscreenBtn.onclick = () => {
            if ((document.fullScreenElement !== undefined && document.fullScreenElement === null) ||
                (document.msFullscreenElement !== undefined && document.msFullscreenElement === null) ||
                (document.mozFullScreen !== undefined && !document.mozFullScreen) ||
                (document.webkitIsFullScreen !== undefined && !document.webkitIsFullScreen)) {

                toggleFullscreenBtn.innerHTML = minimize;

                if (document.documentElement.requestFullScreen) {
                    document.documentElement.requestFullScreen();
                } else if (document.documentElement.mozRequestFullScreen) {
                    document.documentElement.mozRequestFullScreen();
                } else if (document.documentElement.webkitRequestFullScreen) {
                    document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
                } else if (document.documentElement.msRequestFullscreen) {
                    document.documentElement.msRequestFullscreen();
                }
            } else {
                toggleFullscreenBtn.innerHTML = maximize;

                if (document.cancelFullScreen) {
                    document.cancelFullScreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitCancelFullScreen) {
                    document.webkitCancelFullScreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                }
            }
        }
    }


    // Toggle Sidebar
    const setSidebarIconOnly = () => {
        removeClass(body, 'sidebar-hover-only');
        addClass(body, 'sidebar-icon-only');
        localStorage.setItem('sidebarType', 'iconOnly');
        toggleSidebarBtn.innerHTML = alignCenter;
    }
    const setSidebarHoverOnly = () => {
        removeClass(body, 'sidebar-icon-only');
        addClass(body, 'sidebar-hover-only');
        sidebar.find('.collapse.show').collapse('hide');
        localStorage.setItem('sidebarType', 'hoverOnly');
        toggleSidebarBtn.innerHTML = alignJustify;
    }
    const setDefaultSidebar = () => {
        removeClass(body, 'sidebar-hover-only');
        removeClass(body, 'sidebar-icon-only');
        localStorage.setItem('sidebarType', 'default');
        toggleSidebarBtn.innerHTML = alignLeft;
    }

    if(toggleSidebarBtn) {
        toggleSidebarBtn.onclick = () => {
            let sidebarType = localStorage.getItem('sidebarType');

            if (sidebarType === 'iconOnly') {
                setSidebarHoverOnly();
            } else if (sidebarType === 'hoverOnly') {
                setDefaultSidebar();
            } else {
                setSidebarIconOnly();
            }

            activeClassAddInSwitchDrawer();
        }
    }

    // Toggle Theme Mode
    if(toggleThemeBtn) {
        toggleThemeBtn.onclick = () => {
            let theme = htmlElement.getAttribute('theme');
            localStorage.setItem('theme', theme === 'dark' ? 'light' : 'dark');
            toggleTheme();
            activeClassAddInSwitchDrawer();
        };
    }

    // Toggle Diagram Mode - Layout Section
    document.querySelectorAll('.diagram-toggle')
        .forEach(item => {
            item.onclick = ({target}) => {
                let value = target.dataset['value'];
                if (value === 'rtl') {
                    localStorage.setItem('layout', 'rtl')
                    toggleLayout();
                }
                if (value === 'default') {
                    setDefaultSidebar();
                    localStorage.setItem('layout', 'ltr')
                    toggleLayout();
                }
                if (value === 'iconOnly') setSidebarIconOnly();
                if (value === 'hoverOnly') setSidebarHoverOnly();
                location.replace('index.html');
            }
        });

    // Layout Switching
    activeClassAddInSwitchDrawer();
    document.querySelectorAll('.switch-template-theme')
        .forEach(item => {
            item.onclick = ({currentTarget}) => {
                let value = currentTarget.dataset['value'];
                localStorage.setItem('theme', value);
                toggleTheme();
                activeClassAddInSwitchDrawer();
            }
        });
    document.querySelectorAll('.switch-template-layout')
        .forEach(item => {
            item.onclick = ({currentTarget}) => {
                let value = currentTarget.dataset['value'];
                localStorage.setItem('layout', value);
                toggleLayout();
                activeClassAddInSwitchDrawer();
            }
        })
    document.querySelectorAll('.switch-template-sidebar')
        .forEach(item => {
            item.onclick = ({currentTarget}) => {
                let value = currentTarget.dataset['value'];
                if (value === 'iconOnly') setSidebarIconOnly();
                else if (value === 'hoverOnly') setSidebarHoverOnly();
                else setDefaultSidebar();
                activeClassAddInSwitchDrawer();
            }
        })

    // Close other submenu while opening any
    sidebar.on('show.bs.collapse', function (e) {
        $(e.target).parent().parent().find('.collapse.show').collapse('hide');
    });

    // Collapse menu on hover
    $(document).on('mouseenter mouseleave', '.sidebar .nav-item', function (ev) {
        let body = $('body');
        let sidebarIconOnly = body.hasClass("sidebar-icon-only");
        if (!('ontouchstart' in document.documentElement)) {
            if (sidebarIconOnly) {
                let $menuItem = $(this);
                if (ev.type === 'mouseenter') {
                    $menuItem.addClass('hover-open')
                } else {
                    $menuItem.removeClass('hover-open')
                }
            }
        }
    });

    // Close collapse menu when mouse leave from sidebar hover only
    $(document).on('mouseleave', '.sidebar-hover-only .sidebar', function (ev) {
        sidebar.find('.collapse.show').collapse('hide');
    });

    // Prevent dropdown menu from closing inside click
    $(document).on('click.bs.dropdown.data-api', '.dropdown.keep-inside-clicks-open', function (e) {
        e.stopPropagation();
    });
});
