// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type {Banner}
 */
define(['hp/core/UrlFragment',
    'hp/model/Session',
    'hp/services/authn',
    'hp/core/Notifications',
    'hp/core/Uploads',
    'hp/core/MainMenu',
    'hp/view/SearchBoxView',
    'hp/core/HelpMenu',
    'hp/core/Sidebar',
    'hp/core/Performance',
    'hp/model/DevelopmentSettings',
    'hp/core/Localizer',
    'hp/core/EventDispatcher',
    'hp/services/Log',
    'text!hpPages/core/simple_banner.html',
    'text!hpPages/core/banner.html',
    'jquery',
    'lib/jquery.timeago',
    'hp/lib/jquery.hpTooltip'],
function (urlFragment, session, authn, notifications, uploads,
    menu, searchBoxView, help, sidebar, performance, settings, localizer, EventDispatcher, Log,
    simpleBannerHtml, bannerHtml) {"use strict";

    var Banner = (function () {

        var BANNER_CONTAINER = '#hp-banner-container';
        var SESSION_CONTROL = '#hp-session-control';
        var SESSION_FLYOUT = '#hp-session-flyout';
        var SESSION_USER = '#hp-session-user';
        var SESSION_USER_EDIT = '#hp-session-user-edit';
        var SESSION_DURATION_TIME = '#hp-session-duration-time';
        var SESSION_PERFORMANCE_LOCATION = '#hp-session-perf-location';
        var SESSION_PERFORMANCE_DURATION = '#hp-session-perf-duration';
		var SESSION_DURATION = '#hp-session-duration';
        var BODY = '#hp-body-div';
        var LOGOUT = '#hp-session-logout';
        var OTHER_LOGOUT = '.hp-session-logout';
        var TITLE = '.hp-banner h1';
        var ACTIVE = 'hp-active';
        var SELECTED = 'hp-selected';
        var allowLocalLoginDto, defaultProvider, providerInfos = null;

        function Banner() {

            var simpleBanner = $(simpleBannerHtml);
            var banner = $(bannerHtml);
            var reloadOnLogout = true;
            var currentBanner = null;
            var title = null;
            var subTitle = null;
            var userEditHandler = null;
            var dispatcher = new EventDispatcher();

            function hideSession() {
                $(BODY).unbind('click', hideSession);
                $(SESSION_FLYOUT).css('top', - $(SESSION_FLYOUT).outerHeight());
                $(SESSION_FLYOUT, banner).removeClass(ACTIVE);
                $(SESSION_CONTROL).removeClass(SELECTED);
                sidebar.checkFlyouts();
            }

            function showSession() {
                //Based on the providers configured, display the user name.
                if (providerInfos !== null && providerInfos.length > 0) {
                    var selectedProvider = session.getAuthService();
                    if (selectedProvider === "LOCAL") {
                        selectedProvider = localizer.getString('hpsum.common.local');
                    }
                    if (providerInfos.length === 1 && !allowLocalLoginDto.allowLocalLogin) {
                            $(SESSION_USER, banner).text(session.getUser());
                    }
                    else {
                        $(SESSION_USER, banner).text(selectedProvider+"\\"+session.getUser());
                    }
                }
                else {
                    $(SESSION_USER, banner).text(session.getUser());
                }

                var loginTime = session.getLoginTime();
                var lastPerf = performance.getLast();
				var lang = session.getLanguage();
				if ( lang == "ja" || lang == "cn" ){
					$(SESSION_DURATION).html('<time id="hp-session-duration-time"></time> <span>'+localizer.getString('hpsum.common.loggedIn')+'</span>');
					 $(SESSION_DURATION_TIME, banner).attr('datetime', loginTime);
					 $(SESSION_DURATION_TIME, banner).html(loginTime);
					 $(SESSION_DURATION_TIME, banner).timeago();
					 		
				}
				else{
					$(SESSION_DURATION).html('<span>'+localizer.getString('hpsum.common.loggedIn')+'</span> <time id="hp-session-duration-time"></time>');	
					$(SESSION_DURATION_TIME, banner).html(loginTime);
					$(SESSION_DURATION_TIME, banner).attr('datetime', loginTime);
					$(SESSION_DURATION_TIME, banner).timeago();
				}
                if (settings.trackTiming()) {
                    $(SESSION_PERFORMANCE_LOCATION, banner).
                        text(lastPerf.location ? lastPerf.location : '').show();
                    $(SESSION_PERFORMANCE_DURATION, banner).
                        text(lastPerf.duration ? lastPerf.duration : '').show();
                } else {
                    $(SESSION_PERFORMANCE_LOCATION, banner).hide();
                    $(SESSION_PERFORMANCE_DURATION, banner).hide();
                }

                $(SESSION_FLYOUT).css('top', '');
                $(SESSION_FLYOUT, banner).addClass(ACTIVE);
                $(SESSION_CONTROL).addClass(SELECTED);
                sidebar.checkFlyouts();
                // delay to avoid flickering
                setTimeout(function () {$(BODY).bind('click', hideSession);}, 50);
            }

            function logout() {
                authn.logout(session.getToken(), {});
            }
            
            function onSessionChange() {
                $('#hp-session-control .hp-name', banner).
                    text(session.getUser());
            }

            this.init = function (titleArg, subTitleArg, options) {
                title = titleArg;
                subTitle = subTitleArg;

                localizer.localizeDom(simpleBanner);
                localizer.localizeDom(banner);

                $(BANNER_CONTAINER).empty();
                simpleBanner.addClass(ACTIVE);

                $(SESSION_USER_EDIT, banner).hide();
                $(SESSION_USER_EDIT, banner).click(function () {
                    if (userEditHandler) {
                        userEditHandler();
                    }
                });
                $(SESSION_CONTROL, banner).attr('tooltip',
                    localizer.getString('hpsum.common.session')).
                    hpTooltip();
                $(SESSION_CONTROL, banner).click(function (ev) {
                    if (!$(SESSION_CONTROL).hasClass(SELECTED)) {
                        authn.getGlobalSettings({
                            success : function(globalSettingsDto) {
                                allowLocalLoginDto = {
                                    "allowLocalLogin" : globalSettingsDto.allowLocalLogin
                                };
                                defaultProvider = globalSettingsDto.defaultLoginDomain;
                                providerInfos = globalSettingsDto.configuredLoginDomains;
                                showSession();
                            },
                            error : function(errorInfo) {
                                allowLocalLoginDto = null;
                                defaultProvider = null;
                                providerInfos = null;
                                var failureMessage = "Error";
                                dispatcher.fire('getGlobalSettingsError', {
                                    "errorInfo" : errorInfo,
                                    "failureMessage" : failureMessage
                                });
                            }
                        });
                    }
                });

                $(LOGOUT, banner).click(logout);
                $(OTHER_LOGOUT).live('click', logout);
                
                notifications.init(banner, options.notifications);
                uploads.init(banner);
                menu.init(banner, title, subTitle);
                
                if (options.search) {
                    searchBoxView.init(banner);
                } else {
                    $('#hp-search-control', banner).hide();
                }

                help.init(banner);
                sidebar.init();
                
                if (options.showSessionName) {
                    $('#hp-session-control', banner).addClass('hp-full');
                    session.on('authorizationsChanged', onSessionChange);
                }
                
                if (options.subView) {
                    options.subView.init(banner);
                }
            };

            this.setHelp = function (location) {
                help.setLocation(location);
            };

            this.addMenu = function (menuConfig) {
                menu.addMenuItem(menuConfig);
            };

            this.startMenu = function (menuConfig) {
                if (menuConfig.noBanner) {
                    if (null !== currentBanner) {
                        menu.pause();
                        $(BANNER_CONTAINER).empty();
                        currentBanner = null;
                    }
                } else if (menuConfig.simpleBanner) {
                    if (simpleBanner !== currentBanner) {
                        menu.pause();
                        $(BANNER_CONTAINER).empty();
                        $(BANNER_CONTAINER).append(simpleBanner);
                        $(TITLE).text(title);
                        currentBanner = simpleBanner;
                    }
                } else if (menuConfig.consoleBanner) {
                    if (banner !== currentBanner) {
                        $(BANNER_CONTAINER).empty();
                        $(BANNER_CONTAINER).append(banner);
                        menu.resume();
                        currentBanner = banner;
                    }
                    $(banner).addClass('hp-console');
                } else {
                    if (banner !== currentBanner) {
                        $(BANNER_CONTAINER).empty();
                        $(BANNER_CONTAINER).append(banner);
                        menu.resume();
                        currentBanner = banner;
                    }
                    $(banner).removeClass('hp-console');
                }
                menu.startMenuItem(menuConfig);
                searchBoxView.setCategory(menuConfig.indexCategory, menuConfig.label);
                if (menuConfig.localSearch) {
                    searchBoxView.setLocal(menuConfig.localSearch);
                }
            };

            this.finishMenu = function (menuConfig) {
                menu.finishMenuItem(menuConfig);
            };

            this.setDocumentTitle = function (context) {
                var fullTitle = '';
                var menuLabel = menu.getLabel();
                if (context && context.length > 0) {
                    fullTitle += context + ' - ';
                }
                if (menuLabel && menuLabel.length > 0 && '?' !== menuLabel) {
                    fullTitle += menuLabel + ' - ';
                }
                fullTitle += title;
                if (subTitle) {
                    fullTitle += ' - ' + subTitle
                }
                document.title = fullTitle;
            };

            this.getApplicationTitle = function() {
                return title;
            };

            this.setEditUserHandler = function (handler) {
                if (handler) {
                    userEditHandler = handler;
                    $(SESSION_USER_EDIT, banner).show();
                }
                else{
                    userEditHandler = null;
                    $(SESSION_USER_EDIT, banner).hide();
                }
            };

            // for testing
            this.disableReloadOnLogout = function () {
                reloadOnLogout = false;
            };
        }

        return new Banner();
    }());

    return Banner;
});
