/*
 * jde, MenuManager.js, Original coding 19/07/17
 */

'use strict';

var MenuManager = MenuManager || {};

MenuManager = function () {

    var menuItems = [];

    function buildHTMLTopLevelMenuItem( item, topLevelFolder, whereAbouts, appendMode ) {
        var filename = "./" + topLevelFolder + "/" + item.subLevelFolder + "/";
        var html = "<span>";
        html += '<a onclick="loadSnippet(' + "'" + filename + "', '" + whereAbouts + "', " + appendMode + " );" + '">' + item.title + '</a>';
        html += '</span>';
        return html;
    }

    function buildHTMLTopLevelSubMenuItems( item, subFolderName, whereAbouts, appendMode ) {
        var filename = "./" + subFolderName + "/" + item.filename;
        var html = "<li>";
        html += '<a onclick="' + item.function + '(' + "'" + filename + "', '" + whereAbouts + "', " + appendMode + " );" + '">' + item.title + '</a>';
        html += '</li>';
        return html;
    }

// Added Dev 19/07/17
    function loadMenu( filename ) {

        xhr.onreadystatechange = function ( ) {
            if (xhr.readyState==4 && xhr.status==200) {
                var details = JSON.parse( xhr.responseText );
                var topLevelFolder = details.topLevelFolder;
                var topLevelMenuItems = details.topLevelMenuItem;
                var html = "<ul>";
                for ( var index = 0; index < topLevelMenuItems.length; index ++ ) {
                    html += "<li>";
                    var menuItem = topLevelMenuItems[ index ];
                    html += buildHTMLTopLevelMenuItem( menuItem, topLevelFolder, 'SideNavigationShortMenuWrap', false );
                    html += '<ul class="multilevel-linkul-0">';
                    var subMenuItems = menuItem.subLevelItems;
                    var subFolderName = topLevelFolder + "/" + menuItem.subLevelFolder;
                    for ( var subMenuIndex = 0; subMenuIndex < subMenuItems.length; subMenuIndex ++ ) {
                        var subMenuItem = subMenuItems[ subMenuIndex ];
                        html += buildHTMLTopLevelSubMenuItems(subMenuItem, subFolderName, 'SideNavigationLong', false );
                    }
                    html += "</ul>"
                    html += "</li>";
                }
                html += "</ul>";
                console.log( html );
                alert( html );
                showMessage( html, 'HeaderNavigationWrap', false );
/*                
                var filename = details.topLevelFolder + details.filename;
                var where = document.getElementById(whereAbouts);
                var html = "";
                html += '<li><a onclick="loadSnippet(' + "'" + filename + "', 'mainMiddleContentBody', false );" + '">' + details.title + '</a></li>';

                showMessage( '', 'mainMiddleContentFooter', false );   // clear out any slide menu stuff
                if ( details.solutions != "" ) {
                    var solutionFilename = details.contentFolder + details.solutions;
                    html += '<li><a onclick="loadSnippet(' + "'" + solutionFilename + "', 'mainMiddleContentBody', false );" + '">' + details.title + ' solutions.</a></li>';
                }
                if ( details.additional != "" ) {
                    var additionalFilename = details.contentFolder + details.additional;
                    html += '<li><a onclick="loadSnippet(' + "'" + additionalFilename + "', 'mainMiddleContentBody', false );" + '">' + details.title + ' more exercises.</a></li>';
                }
                console.log( html );
                showMessage( html, whereAbouts, appendMode );
*/                
            }
        }
        xhr.open("GET", filename, true);
        xhr.send();
    }
    
    // function executed when the state of the request changes
    function handleStateChangeMenu(whereAbouts, preText, postText, appendMode) {
        debug('handleStateChangeMenu:' + whereAbouts + preText + postText + appendMode);
        // continue if the process is completed

        if (xhr.readyState == 4) {
            // continue only if HTTP status is "OK"
            if ((xhr.status >= 200 && xhr.status < 300) || (xhr.status == 304)) {
                try { // now place response in the chosen area of the page if found
                    var where = document.getElementById(whereAbouts);
                    if (where != null) {
                        // build the response
                        var responsTxt = preText + xhr.responseText + postText;
//alert( 'handleStateChangeText responseText:'+ responsTxt + ':' );
                        showMessage(responsTxt, whereAbouts, appendMode);
                        processMenuItems();     // now everything is done we can do the revursive call
                    } else {
                        throw new Error('Error :' + whereAbouts + ' not found on page!');
                    }
                } catch (e) {
                    // display error message
                    showMessage(e.name + "(handleStateChangeText)Error reading the response:" + e.toString(), 'debugArea', true);
                }
            }
            else {
                // display status message
                showMessage("(handleStateChangeText)There was a problem retrieving the data:\n" + xhr.statusText + " (" + xhr.statusCode + ") ", 'debugArea', true);
            }
        }
    }

    function getMenuSnippet(pathname, whereAbouts, appendMode) {
        debug( 'getMenuSnippet:' + pathname +':' +whereAbouts + ':');
        try {
            // initiate server request
            var url = pathname;
            xhr.open("GET", url, true); 				// true => asynchronous call
            xhr.onreadystatechange = function () {
                var preText = '', postText = '';
                handleStateChangeMenu(whereAbouts, preText, postText, appendMode);
            }
            xhr.send(null);
        }
            // display an error in case of failure
        catch (e) {
            showMessage("Can't connect to server:\n" + e.toString(), 'debugArea', true);
        }
    }

    function processMenuItem( item ) {
        if ( item != null ) {
            getMenuSnippet( item.pathname, item.whereAbouts, item.addMode );
            console.log( item.pathname + ' ' + item.whereAbouts );
        }
    }

    function processMenuItems( ) {
        console.log( 'processMenuItems|menuItems:', menuItems.length );
        if ( menuItems.length > 0 ) {
            var item = menuItems.shift();
            console.log( 'processMenuItems|item:', item );
            console.log( 'processMenuItems|menuItems:', menuItems.length );
            processMenuItem( item );
            // processMenuItems();     // Normally recursive call would go here but its asynchronous so do later
        }
    }

    var mainMenu = function( whereAbouts ) {
        xhr = createXMLHttpRequestObject();
        loadMenu( './dsa/mainMenu.json' );
    }

    return {
        startup : "Menu start up ok",
        load: mainMenu( )
    }

}();
