// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define([
	'hp/model/Session',
	'hpsum/presenter/baseline/BaselinePresenter',
  	'hpsum/presenter/node/NodePresenter',
  	'hpsum/presenter/group/GroupPresenter',
	'hp/core/Notifications',
  	'hp/core/Localizer',
	'jquery',
  	'hp/lib/jquery.hpSelect'],
function(session, BaselinePresenter, NodePresenter, GroupPresenter, notifications, localizer) { "use strict";

    var WelcomeView = (function() {
    	
    	var UNSUPPORTED_BROWSER = '#hpsum-unsupported-browser',
		HPSUM_MAIN_MENU_CONTROL = '#hp-main-menu-control',
		HPSUM_MAIN_MENU_CONTROL_TOOLTIP = '#hp-main-menu-control-tooltip',
		HPSUM_MENU_GUIDE_CLOSE = '#hpsum-menu-guide-close',
		HPSUM_LOCALHOST_GUIDED_UPDATE = '#select-guided-update',
		HPSUM_LOCALHOST_GUIDED_UPDATE_TOOLTIP = '#select-guided-update-tooltip',
		HPSUM_BASELINE_LIBRARY = '#select-baseline',
		HPSUM_BASELINE_LIBRARY_TOOLTIP = '#select-baseline-tooltip',
		HPSUM_NODES = "#select-node",
		HPSUM_ILO_FEDERATED_UPDATE = "#select-ilofederation",		
		IN_HOME_SCREEN = true,
		showActivity_defaultNode = true,
		showActivity_defaultBaseline = true;
		     
        /**
         * Constructor
         */
        function WelcomeView() {
        	
        	/**
             * @private
             */         
          	
          	//Parse the navigator object's userAgent string and return the browser type & version
          	function getBrowser() {
				    var ua = navigator.userAgent.toLowerCase();
				
				    var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
				        /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
				        /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
				        /(msie) ([\w.]+)/.exec( ua ) ||
				        ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
				        [];
				        
				        //Workaround for ie11, identify the layout engine 'Trident'
				        if(ua.match(/trident/i)) {
				            match [ 1 ] = 'msie';
				        }
				
				    return {
				        browser: match[ 1 ] || "",
				        version: match[ 2 ] || "0"
				    };
			}
			
			function isBrowserSupported(browserObj) {
				if(browserObj.browser == 'msie' || browserObj.browser == 'mozilla' || browserObj.browser == 'chrome') {
					return true;
				} else {
					return false;
				}
			}
			
			function isPlatformLinux() {
			    if(navigator.platform.match(/linux/i)) {
			        return true;
			    } else {
			        return false;
			    }
			}
				
			function isBrowserVerSupported(browserObj) {			
				if (browserObj.browser == 'msie' && parseInt(browserObj.version) < 9) {
					return false;
				} else if (browserObj.browser == 'mozilla' && parseInt(browserObj.version) < 18 && !isPlatformLinux()) {
					return false;
				} else if (browserObj.browser == 'mozilla' && parseInt(browserObj.version) < 17 && isPlatformLinux()) {
                    return false;
                } else if (browserObj.browser == 'chrome' && parseInt(browserObj.version) < 24) {
					return false;
				} else {
					return true;
				}
			}
			
 			function updateUserInterfaceForOEM()
			{
				var sessionDataHandlers = {
					success : function(data) {
						// if hcode is 0 then session is alive and set session cookies
						if(data.hapi.hcode == 0) {
							var mfg = data.hapi.manufacturer;
							if (mfg != "HP") {
								// Remove iloFederated Update from 'Select otion'
								$(".hp-aspects #select-ilofederation").remove();
								$(".hp-section [href='#/ilofederation']").remove();
								
							}
						}
						else
						{
							// if session is expired or any other error, then goto login page
							session.eraseAll();
							document.location.href = "/#/login";
						}
					},
					error : function(jqXHR) {
						// getsessiondata failed, so goto login page
						session.eraseAll();
						document.location.href = "/#/login";
					}
				};

				//get session data and set user and login details for the session
				session.getSessionData(sessionDataHandlers);
			}
			
			function getGuideTextdetails()
			{
				var sessionDataHandlers = {
		                success : function(data) {
							//if hcode is 0 then session is alive and set session cookies
		                    if(data.hapi.hcode == 0) {	
								if(IN_HOME_SCREEN == true){
									var firstTimeLaunch;
									var isAnyBaselinePresent;
									var isDefaultBaselinePresent;
									var showMainMenuUiGuide;
									var hapi = data.hapi;
									if(hapi.hasOwnProperty('firstTimeLaunch'))
									{
									firstTimeLaunch = hapi.firstTimeLaunch;
									}
									if(hapi.hasOwnProperty('isAnyBaselinePresent'))
									{
									isAnyBaselinePresent = hapi.isAnyBaselinePresent;
									}
									if(hapi.hasOwnProperty('isDefaultBaselinePresent'))
									{
									isDefaultBaselinePresent = hapi.isDefaultBaselinePresent;
									}
									if((hapi.session_settings).hasOwnProperty('showMainMenuUiGuide'))
									{
										showMainMenuUiGuide = hapi.session_settings.showMainMenuUiGuide;
									}
									if (showMainMenuUiGuide == true)
									{
										 $(HPSUM_MAIN_MENU_CONTROL).attr('tooltip_menu', '<div id="hpsum-menu-guide-close" style="float:right;display:inline-block;width: 10px; height: 10px;background-image: url(\'../../img/hp-piano/hp-piano-icons.png\');background-position: -160px -40px;background-repeat: no-repeat;"></div><div>'+localizer.getString('hpsum.common.menuGuide')+'</div>').hpTooltip(); 
										 $(HPSUM_MAIN_MENU_CONTROL).trigger('mouseenter');
										 var width = parseInt($(HPSUM_MAIN_MENU_CONTROL).css('width'));
										 $(HPSUM_MAIN_MENU_CONTROL_TOOLTIP).css({'z-index':'0','left': 2*width/3+'px'}); 
										 $(HPSUM_MAIN_MENU_CONTROL_TOOLTIP).hide().delay(1000).fadeIn(2000);
										 $(HPSUM_MAIN_MENU_CONTROL).trigger('mouseleave');
									}
									else{									
									}
									if((firstTimeLaunch == true) && (isDefaultBaselinePresent == true))
									{
										$(HPSUM_LOCALHOST_GUIDED_UPDATE).attr('tooltip_menu', localizer.getString('hpsum.common.localHostGuidedUpdateGuide')).hpTooltip(); 
										$(HPSUM_LOCALHOST_GUIDED_UPDATE).trigger('mouseenter');
										$(HPSUM_LOCALHOST_GUIDED_UPDATE_TOOLTIP).css('z-index','0');
										resizeGuide(HPSUM_LOCALHOST_GUIDED_UPDATE,HPSUM_LOCALHOST_GUIDED_UPDATE_TOOLTIP);
										$(HPSUM_LOCALHOST_GUIDED_UPDATE_TOOLTIP).hide().delay(1000).fadeIn(2000);
										$(HPSUM_LOCALHOST_GUIDED_UPDATE_TOOLTIP).removeClass('hp-above').addClass('hpsum-above-right');
										$(HPSUM_LOCALHOST_GUIDED_UPDATE).trigger('mouseleave');
										if( showActivity_defaultBaseline == true ) {
											var default_baseline =  hapi.session_settings.report_dir;
											var message = default_baseline + " " + localizer.getString('hpsum.oneTouchUpdate.baselineAdded');
											notifications.show(message, 'ok');
											showActivity_defaultBaseline = false;
										}
									}
									else{									
									}
									if(isAnyBaselinePresent == false)
									{
										$(HPSUM_BASELINE_LIBRARY).attr('tooltip_menu', localizer.getString('hpsum.common.baselineLibraryGuide')).hpTooltip(); 
										$(HPSUM_BASELINE_LIBRARY).trigger('mouseenter');
										$(HPSUM_BASELINE_LIBRARY_TOOLTIP).css('z-index','0');
										resizeGuide(HPSUM_BASELINE_LIBRARY,HPSUM_BASELINE_LIBRARY_TOOLTIP);
										$(HPSUM_BASELINE_LIBRARY_TOOLTIP).hide().delay(1000).fadeIn(2000);
										$(HPSUM_BASELINE_LIBRARY_TOOLTIP).removeClass('hp-above').addClass('hpsum-above-right');
										$(HPSUM_BASELINE_LIBRARY).trigger('mouseleave');
										
									}
									else{
									}
									if( firstTimeLaunch == true && showActivity_defaultNode == true ) {
										var message = localizer.getString('hpsum.oneTouchUpdate.localhost') + localizer.getString('hpsum.node.nodesAddedSuccessfully');
										notifications.show(message, 'ok');
										showActivity_defaultNode = false;
									}
								}
							}
		                    else
		                    {
		                    	//if session is expired or any other error, then goto login page
		                    	session.eraseAll();
		                    	document.location.href = "/#/login";
		                    }
		                },
		                error : function(jqXHR) {
		                	//getsessiondata failed, so goto login page
		                    session.eraseAll();
		                    document.location.href = "/#/login";
		                }
		       	};
		       	
				//get session data and set user and login details for the session
				session.getSessionData(sessionDataHandlers);
			}
			
			function updateUserSessionDetails()
			{
				var sessionDataHandlers = {
		                success : function(data) {
		                    
		                    //if hcode is 0 then session is alive and set session cookies
		                    if(data.hapi.hcode == 0) {
		                  	   	//save user name in the session cookie
		                    	session.saveUser(data.hapi.username)

                          session.saveSesionLanguage(data.hapi.language);
		                    	
		                    	//save login time in the session cookie
		                    	var loggedinTime = Date.parseISOString(data.hapi.timeLoggedIn);
		                    	session.saveLoginTime(loggedinTime.toISOString());
								var mfg = data.hapi.manufacturer;
								session.saveManufacturer(mfg);
								if (mfg != "HP") {
									// Remove iloFederated Update from 'Select otion'
									$(".hp-aspects #select-ilofederation").remove();
									$(".hp-section [href='#/ilofederation']").remove();
									//hide the HP copyright
									$('.hp-confidential').hide();
								}
							}
		                    else
		                    {
		                    	//if session is expired or any other error, then goto login page
		                    	session.eraseAll();
		                    	document.location.href = "/#/login";
		                    }
		                },
		                error : function(jqXHR) {
		                	//getsessiondata failed, so goto login page
		                    session.eraseAll();
		                    document.location.href = "/#/login";
		                }
		       	};
		       	
				//get session data and set user and login details for the session
				session.getSessionData(sessionDataHandlers);
				
			}
			      	
            /**
             * @public
             */
            this.pause = function () {
				IN_HOME_SCREEN = false;
				removeToolTipAttrAndClass(HPSUM_MAIN_MENU_CONTROL,HPSUM_MAIN_MENU_CONTROL_TOOLTIP);
				removeToolTipAttrAndClass(HPSUM_LOCALHOST_GUIDED_UPDATE,HPSUM_LOCALHOST_GUIDED_UPDATE_TOOLTIP);
				removeToolTipAttrAndClass(HPSUM_BASELINE_LIBRARY,HPSUM_BASELINE_LIBRARY_TOOLTIP);
            };
			
            function resizeGuide(source, tip)
			{
				var tooltipPointerOffset = 10; //the tooltip pointer is off by 10px from the right side of the tooltip. Adjusting for it.
				source = $(source);
				var sourceCount = source.length;
				tip = $(tip);
				var tipCount = tip.length;
				if(source && tip && sourceCount && tipCount){ //Check whether the object is actually there
					var sourceLeft = source.offset().left;
					var sourceTop = source.offset().top;
					var tipBottom = $(window).height()- (sourceTop);
					var tipRight = $(window).width()- (sourceLeft)-(tooltipPointerOffset)-(source.width())/2;
					tip.css('bottom',tipBottom+'px');
					tip.css('right',tipRight+'px');
					tip.css('left','auto');
					tip.css('top','auto');
					tip.css('width','auto');
				}	
			}
			
			function removeToolTipAttrAndClass(source,tip){
				source = $(source);
				tip = $(tip);
				source.removeClass('hp-tooltipped').removeAttr('tooltip_menu data-tooltip');
				if(tip.length > 0)
					{
						tip.remove();
					}
			}
			
            this.resume = function () {
				IN_HOME_SCREEN = true;
				$('#hp-overlay').removeClass('hp-active');
				document.title = localizer.getString('hpsum.title' ) + hpsumShortVersionStr;
				getGuideTextdetails();	
				$(window).resize(function() {	
					if($(HPSUM_BASELINE_LIBRARY).length >0)
					{	
						resizeGuide(HPSUM_BASELINE_LIBRARY,HPSUM_BASELINE_LIBRARY_TOOLTIP);
					}
					if($(HPSUM_LOCALHOST_GUIDED_UPDATE).length > 0)
					{
						resizeGuide(HPSUM_LOCALHOST_GUIDED_UPDATE,HPSUM_LOCALHOST_GUIDED_UPDATE_TOOLTIP);
					}
				});
				$('.hp-page-contents').scroll(function(){
					if($(HPSUM_BASELINE_LIBRARY).length >0)
					{	
						resizeGuide(HPSUM_BASELINE_LIBRARY,HPSUM_BASELINE_LIBRARY_TOOLTIP);
					}
					if($(HPSUM_LOCALHOST_GUIDED_UPDATE).length > 0)
					{
						resizeGuide(HPSUM_LOCALHOST_GUIDED_UPDATE,HPSUM_LOCALHOST_GUIDED_UPDATE_TOOLTIP);
					}
				});	
				
				//Changes for OEM Rebranding
				//LocalHost GuidedUpdate Image
				$(HPSUM_LOCALHOST_GUIDED_UPDATE).on({
				mouseenter : function(){
					$(HPSUM_LOCALHOST_GUIDED_UPDATE).find("img").attr("src","/img/hp-sum/home-one-touch-update-hov.png?BMN=");
				},
				mouseleave : function(){
					$(HPSUM_LOCALHOST_GUIDED_UPDATE).find("img").attr("src","/img/hp-sum/home-one-touch-update.png?BMN=");
				}
				});
				//Select Baseline Image
				$(HPSUM_BASELINE_LIBRARY).on({
				mouseenter : function(){
					$(HPSUM_BASELINE_LIBRARY).find("img").attr("src","/img/hp-sum/home-baselines-hov.png?BMN=");
				},
				mouseleave : function(){
					$(HPSUM_BASELINE_LIBRARY).find("img").attr("src","/img/hp-sum/home-baselines.png?BMN=");
				}
				});
				//Select Node image
				$(HPSUM_NODES).on({
				mouseenter : function(){
					$(HPSUM_NODES).find("img").attr("src","/img/hp-sum/home-nodes-hov.png?BMN=");
				},
				mouseleave : function(){
					$(HPSUM_NODES).find("img").attr("src","/img/hp-sum/home-nodes.png?BMN=");
				}
				});
				//iLo Federated Update Image
				$(HPSUM_ILO_FEDERATED_UPDATE).on({
				mouseenter : function(){
					$(HPSUM_ILO_FEDERATED_UPDATE).find("img").attr("src","/img/hp-sum/home-dashboard-hov.png?BMN=");
				},
				mouseleave : function(){
					$(HPSUM_ILO_FEDERATED_UPDATE).find("img").attr("src","/img/hp-sum/home-dashboard.png?BMN");
				}
				});
								
			};
            
            this.init = function () {
                //document.title = 'Welcome';
                //$('.hp-button.hp-primary').focus();
                var browserObj = getBrowser();
                
                if(!isBrowserSupported(browserObj)){
                	$(UNSUPPORTED_BROWSER).removeClass('hp-disabled');
                	$(UNSUPPORTED_BROWSER).html('<h2></h2><div class=\"hp-notify hp-notify-warning hp-active\" style=\"background-color:#fffdd7\"><p><b>'+ localizer.getString('hpsum.common.unsupportedBrowser') +'</b></p></div>')                	
                } else if (!isBrowserVerSupported(browserObj)){
                	$(UNSUPPORTED_BROWSER).removeClass('hp-disabled');
                	$(UNSUPPORTED_BROWSER).html('<h2></h2><div class=\"hp-notify hp-notify-warning hp-active\" style=\"background-color:#fffdd7\"><p><b>'+ localizer.getString('hpsum.common.unsupportedBrowserVersion') +'</b></p></div>')                	
                } else if (screen.width < 1024 || screen.height < 768) {
                    $(UNSUPPORTED_BROWSER).removeClass('hp-disabled');
                    $(UNSUPPORTED_BROWSER).html('<h2></h2><div class=\"hp-notify hp-notify-warning hp-active\" style=\"background-color:#fffdd7\"><p><b>'+ localizer.getString('hpsum.common.minimumResolutionWarning') +'</b></p></div>')
                }
                
				//update logged in user name and logged in time in the user session pane
                updateUserSessionDetails();				
				$(HPSUM_MENU_GUIDE_CLOSE).live('click',function()
				{
					$(HPSUM_MAIN_MENU_CONTROL_TOOLTIP).fadeOut(1000, function() {
						removeToolTipAttrAndClass(HPSUM_MAIN_MENU_CONTROL,HPSUM_MAIN_MENU_CONTROL_TOOLTIP);
						session.setMainMenuGuideText(false);
					});
				});
						                                                           
                this.resume();  
            };
        }

        return WelcomeView;
    }());   
    return new WelcomeView();
});
