// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type {MainMenu}
 */
define(['hp/model/Session',
    'hp/core/LinkTargetBuilder',
    'hp/core/Localizer',
    'hp/services/Log',
    'text!hpPages/core/main_menu.html',
    'text!hpPages/core/page_sub_nav.html',
    'text!hpPages/core/page_label.html',
    'fs/presenter/settings/ApplianceUpdatePresenter',
    'hp/core/Notifications',
    'lib/jquery.cookie',
    'jquery'],
function (session, linkTargetBuilder, localizer, Log,
    mainMenuHtml, pageSubNavHtml, pageLabelHtml, upgradePresenter, notifications) { "use strict";

    var MainMenu = (function () {

        var CONTROL = '#hp-main-menu-control';
        var LABEL = '#hp-main-menu-label';
        var SUB_LABEL = '#hp-main-menu-sub-label';
        var SEARCH = '#hp-search';
        var MENU = '#hp-main-menu';
        var LINK = '#hp-main-menu a';
        var BODY = '#hp-body-div';
        var SECTIONS = MENU + " .hp-sections";
        var SECTION = ".hp-section";
        var SECTION_TEMPLATE = "#hp-menu-section-template";
        var ITEM_TEMPLATE = "#hp-menu-item-template";
        var SIDEBAR = '#hp-sidebar';
        var ACTIVE = "hp-active";
        var SELECTED = "hp-selected";
        var UNAUTHORIZED = "hp-unauthorized";
        var EXPERIMENTAL = "hp-experimental";
        var UPGRADE = "upgrade";
        var USER = "user";
        var UPGRADEREFRESH= "upgradeRefresh";

        function MainMenu() {

            var banner;
            var title;
            var subTitle;
            var pageSubNav = $(pageSubNavHtml);
            var pageLabel = $(pageLabelHtml);
            var disableMenu = false;
            var configs = {};    // location -> configuration
            var sections = {}; // section name -> section DOM object
            var sectionTemplate = null;
            var itemTemplate = null;
            var label = null;

            // private
            function hideMenu() {
                $(BODY).unbind('click', hideMenu);
                $(MENU, banner).removeClass(ACTIVE).css('width', '');
                $(CONTROL, banner).removeClass(SELECTED).css('width', '');
                $(SIDEBAR).removeClass('hp-inactive');
            }

            // private
            function showMenu() {
                // IE9 and IE10 have an off by one problem, add one for them
                var width = Math.max($(CONTROL, banner).outerWidth(),
                    $(MENU, banner).outerWidth()) + 1;
                if (! disableMenu) {
                    $(MENU, banner).addClass(ACTIVE).css('width', width);
                    $(CONTROL, banner).addClass(SELECTED).css('width', width);
                    $(SIDEBAR).addClass('hp-inactive');
                    // delay to avoid flickering
                    setTimeout(function () {$(BODY).bind('click', hideMenu);}, 50);
                }
            }

            function anchorForMenuLocation(menuLocation) {
                return $(LINK + '[href="#' + menuLocation + '"], ' +
                  LINK + '[href="#' + menuLocation + '/"]', banner);
            }

            function deactivate() {
                $(CONTROL, banner).removeClass(ACTIVE);
                disableMenu = true;
                $(SEARCH, banner).hide();
            }

            function activate() {
                $(CONTROL, banner).addClass(ACTIVE);
                disableMenu = false;
                $(SEARCH, banner).show();
            }

            // private
            function onAuthorizationsChanged() {

                // Hide the menu items for which the
                // current user has no VIEW permission.
                $.each(configs, function (index, menuConfig) {
                    var anchor;
                    if (menuConfig.authCategory) {
                        anchor = anchorForMenuLocation(menuConfig.location);
                        if (session.canViewCategory(menuConfig.authCategory)) {
                            // show the <a> tag and its <li> parent.
                            $(anchor).closest('li').removeClass(UNAUTHORIZED);
                        } else {
                            // hide the <a> tag and its <li> parent.
                            $(anchor).closest('li').addClass(UNAUTHORIZED);
                        }
                    }
                });

                // if all items are UNAUTHORIZED, then the section is too
                $.each($(SECTION, banner), function(index, section) {
                    if ($('li', section).length ===
                        $('li.' + UNAUTHORIZED, section).length) {
                        $(section).parent().addClass(UNAUTHORIZED);
                    }
                    else {
                        $(section).parent().removeClass(UNAUTHORIZED);
                    }
                });
            }

            // public
            this.init = function (bannerArg, titleArg, subTitleArg) {
                var mainMenu = $(mainMenuHtml);
                localizer.localizeDom(mainMenu);

                banner = bannerArg;
                banner.append(mainMenu);
                title = titleArg;
                subTitle = subTitleArg;
                session.on("authorizationsChanged", onAuthorizationsChanged);

                if ($(ITEM_TEMPLATE, banner).length > 0) {
                    itemTemplate = $(ITEM_TEMPLATE, banner);
                    itemTemplate.removeAttr('id').detach().removeClass('hp-template');
                    sectionTemplate = $(SECTION_TEMPLATE, banner);
                    sectionTemplate.removeAttr('id').detach().removeClass('hp-template');
                } else {
                    $(CONTROL, banner).removeClass('hp-disabled');
                }

                $(LABEL, banner).text(title);
                if (subTitle) {
                    $(SUB_LABEL, banner).text(subTitle);
                }
            };

            function onControlClick(ev) {
                if (!$(CONTROL, banner).hasClass('hp-disabled') &&
                    !$(CONTROL, banner).hasClass(SELECTED)) {
                    showMenu();
                }
            }

            this.pause = function () {
                removeEvents();
                $(CONTROL, banner).off('click', onControlClick);
            };

            function getUpgradeStatus(){
               // upgradePresenter.getUpgradeStatus();
            }


            function registerEvents(){
                upgradePresenter.on('getUpgradeStatusSuccess',onUpgradeStatusSuccess);
            }

            /*
             * Un-Register Events
             */
            function removeEvents(){
                upgradePresenter.off('getUpgradeStatusSuccess',onUpgradeStatusSuccess);
            }

            function onUpgradeStatusSuccess(data){
                if (data === null)
                {
                    return false;
                }
                var displayUpgradeStatus,
                    version = data.version.split(",")[0],
                    latestUpgradeDate = data.upgradeDate,
                    upgrade = $.cookie(UPGRADE),
                    user = $.cookie(USER).toLowerCase(),
                    upgrade_details = user +":"+latestUpgradeDate;

                if (upgrade_details != upgrade )
                {
                    if($.cookie(UPGRADEREFRESH) === "true" || $.cookie(UPGRADEREFRESH)=== undefined){
                        $.cookie(UPGRADEREFRESH, false);
                        window.location.reload(true);
                    }
                    else {
                        $.cookie(UPGRADE,upgrade_details);
                        if (data.success) {
                            displayUpgradeStatus = {
                                    summary : localizer.getString('fs.settings.appliance.update.updateAppliance'),
                                    status : "ok",
                                    timestamp : data.upgradeDate,
                                    changing : false,
                                    details : version
                            };
                        }
                        else {
                            displayUpgradeStatus = {
                                    summary : localizer.getString('fs.settings.appliance.update.updateAppliance'),
                                    timestamp : data.upgradeDate,
                                    status : "error",
                                    changing : false,
                                    details : localizer.getString('fs.settings.appliance.update.applianceUpdateFailed')
                            };
                        }
                        notifications.add(displayUpgradeStatus,true);
                        $.cookie(UPGRADEREFRESH, true);
                    }
                }
            }


            this.resume = function () {
                 registerEvents();
                 getUpgradeStatus();
                $(CONTROL, banner).on('click', onControlClick);
            };

            this.addMenuItem = function (menuConfig) {
                var section, item, sectionId;

                configs[menuConfig.location] = menuConfig;
                linkTargetBuilder.addMenuItem(menuConfig);

                sectionId = menuConfig.footer ? 'admin' : menuConfig.section;

                if (sectionTemplate && (sectionId || '' === sectionId)) {
                    section = sections[sectionId];
                    if (! section) {
                        section = sectionTemplate.clone();
                        sections[sectionId] = section;
                        if (! menuConfig.section) {
                            // add a blank label if there are other labels
                            if ($('.hp-sections > li > label', banner).length > 0) {
                                $('label', section).html('&nbsp');
                            }
                        } else {
                            $('label', section).text(menuConfig.section);
                        }
                        $(SECTIONS, banner).append(section);
                    }
                    item = itemTemplate.clone();
                    if (menuConfig.experimental) {
                        item.addClass(EXPERIMENTAL);
                    }
                    $('a', item).attr('href', '#' + menuConfig.location);
                    $('a', item).text(menuConfig.label);
                    $(SECTION, section).append(item);

                    // if all items are experimental, then the section is too
                    if ($(SECTION + ' li', section).length ===
                        $(SECTION + ' li.' + EXPERIMENTAL).length) {
                        section.addClass(EXPERIMENTAL);
                    } else {
                        section.removeClass(EXPERIMENTAL);
                    }
                    $(CONTROL, banner).removeClass('hp-disabled');
                }
            };

            this.getMenuItems = function () {
                return configs;
            };

            this.startMenuItem = function (menuConfig) {
                var anchor;
                label = '?';

                hideMenu();

                $(LINK, banner).removeClass(SELECTED);

                if (menuConfig.location) {
                    if (menuConfig.label) {
                        label = menuConfig.label;
                    }
                    // figure out which link matches and set the button to that
                    // figure out which link in the menu has the hash for the location
                    anchor = anchorForMenuLocation(menuConfig.location);
                    if (anchor.length > 0) {
                        if ($(anchor).closest('li').hasClass('hp-hidden')) {
                            deactivate();
                        } else {
                            anchor.addClass(SELECTED);
                            activate();
                        }
                    } else {
                        Log.warn("No menu item for " + menuConfig.location);
                        activate();
                    }
                } else if (! menuConfig.simpleBanner) {
                    Log.warn("No menu location");
                    activate();
                }

                // adjust banner search left for when page name is too wide
                $('#hp-search-control, #hp-search-menu', banner).
                    css('left', $(CONTROL, banner).outerWidth());
                // adjust banner search width on right depending upon the icons
                $('#hp-search-menu', banner).
                    css('right', $('#hp-main-banner .hp-header-secondary').outerWidth());
                $('.hp-header-primary', banner).
                    css('right', $('.hp-header-secondary', banner).outerWidth());
            };

            this.finishMenuItem = function (menuConfig) {
                if (!menuConfig.noBanner && !menuConfig.simpleBanner && label !== '?') {
                    if (! $('.hp-page').hasClass('hp-full-page')) {
                        if ($('.hp-page > .hp-sub-nav').length === 0) {
                            // give the page a sub-nav if it doesn't have one
                            $('.hp-page').prepend(pageSubNav);
                        } else if ($('.hp-page > .hp-sub-nav > .hp-page-label').length === 0) {
                            // give the page a label if it doesn't have one
                            if ($('.hp-page > .hp-sub-nav > .hp-filterbar-control').length === 0) {
                                $('.hp-page > .hp-sub-nav').prepend(pageLabel);
                            } else {
                                $('.hp-page > .hp-sub-nav > .hp-filterbar-control').after(pageLabel);
                            }
                        }
                        $('.hp-page-label h1').text(label);
                    }
                }
            };

            this.getLabel = function () {
                return label;
            };
        }

        return new MainMenu();
    }());

    return MainMenu;
});
