///////////////////////////
// Configure Titlization //
///////////////////////////
var TITLEIZE = false;

(function(document) {
    'use strict';

    /**
     * Support for document ready
     */
    function documentReady(fn) {
        if (document.readyState != 'loading') {
            fn();
        } else {
            document.addEventListener('DOMContentLoaded', fn);
        }
    }

    /** 
     * Underscore string's titleize.
     */ 
    function titleize(str) {
        return decodeURIComponent(str).toLowerCase().replace(/(?:^|\s|-)\S/g, c => c.toUpperCase());
    }
    
    /**
     * Set the title and build breadcrumb according to
     * current location.
     */
    function setTitle() {
        let cleanPath       = decodeURIComponent(window.location.pathname.replace(/\/$/g, '')),
            titleText, 
            breadcrumbHtml  = '', 
            index           = 0, 
            origin          = window.location.origin + '/';
        
        if (cleanPath) {
            let parts = cleanPath.split('/');
            cleanPath = parts[parts.length - 1];
            titleText = (TITLEIZE) ? titleize(cleanPath).replace(/-|_/g, ' ') : cleanPath;

            breadcrumbHtml += '<a href="' + origin + '">Home</a><span class="separator">/</span>'
            parts.forEach((name) => {
                if (name){
                    origin += name + '/';
                    breadcrumbHtml += '<a ';

                    if (index == parts.length -1){
                        breadcrumbHtml += 'class="active" ';
                    }
                    breadcrumbHtml += 'href="' + origin + '">' + name + '</a><span class="separator">/</span>'
                }
                index++;
            });
        } else {
            titleText = window.location.host;
        }

        titleText = `Index of ${titleText}`;

        const titleContainer = document.querySelector('h1#title');
        const breadContainer = document.querySelector('div#breadcrumb');

        if (titleContainer) titleContainer.innerHTML = titleText;
        if (breadContainer) breadContainer.innerHTML = breadcrumbHtml;
        document.title = titleText;
    }

    /**
     * Handle search input change.
     */
    function onSearchInputChange(e) {

        let input       = e.target,
            closeButton = document.querySelector('.close-search'),
            hidden      = 0,
            matchs      = 0,
            val         = input.value.toLowerCase(),
            rowNoItem   = document.querySelector('table#list tBody tr.no-items');

        if (!rowNoItem){
            let row = document.createElement('tr');
            row.classList.add('no-items');
            row.innerHTML = '<td colspan="5">No matching items</td>';
            document.querySelector('table#list tBody').appendChild(row);
            rowNoItem = row;
        }
        if (val.length == 0){
            cleanSearch();
            return;
        }

        document.querySelectorAll('table#list tBody tr').forEach(row => {
            if (row.classList.contains('indexbreakrow') || row.classList.contains('indexhead')) {
                return;
            } 

            let text = row.textContent.toLowerCase();
            if (text.indexOf(val) === -1 || row.classList.contains('even-parentdir')) {
                row.classList.add('hidden');
                hidden++;
            } else {
                row.classList.remove('hidden');
                matchs++;
            }
        });

        closeButton.classList.toggle('active', val.length > 0)
        rowNoItem.classList.toggle('hidden', matchs > 0)

    }

    /**
     * Clean search and restore filtered elements.
     */
    function cleanSearch() {
        document.querySelectorAll('table#list tBody tr').forEach(element => {
            if (element.classList.contains('no-items')){
                element.classList.add('hidden');
            } else {
                element.classList.remove('hidden');
            }
        });
        document.querySelector('.close-search').classList.remove('active');
        document.querySelector('input#filter').value = '';
        document.querySelector('input#filter').focus();
    }

    /**
     * Removes the NGINX given breadcrumb and renames the parent directory text..
     */
    function editText() {
        let dom = document.querySelector("#section-content .row");
        dom.innerHTML = dom.innerHTML.substring(dom.innerText.substring(1).search("\n")+3);
        dom = document.querySelector("tbody a[href$='../']").innerText = "Parent Directory"
    }

    /**
     * Start
     */
    documentReady(function(){
        setTitle();
        editText();
        document.querySelector('input#filter').addEventListener('input', onSearchInputChange);
        document.querySelector('.close-search').addEventListener('click', cleanSearch);
    });

})(document);
