// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type (BaselinePresenter)
 * This is presenter class for Baseline resource.
 * Provides functions for adding a new baseline item into IndexService and Deleting an existing baseline item from IndexService
 */
define(['hpsum/model/baseline/BaselineResource',
	'hp/core/LinkTargetBuilder',
	'hp/services/IndexService',
	'hp/core/Router',
	'hp/core/UrlFragment',
	'hp/core/Notifications',
	'hp/core/EventDispatcher',
    'hp/services/Log',
	'hp/services/REST', 
    'hp/model/Session',
    'hp/core/Localizer'],
function(resource, linkTargetBuilder, indexService, router, urlFragment, notifications, EventDispatcher, log, restapi , session, localizer) {"use strict";

    var BaselinePresenter = ( function() {

        // consts/statics can go here.
        //

        /**
         * @constructor
         * @type {BaselinePresenter}
         */
        function BaselinePresenter() {

            var dispatcher = new EventDispatcher();
	    var selectedName = '';
            var baselines = [], iterator;
			var lastLocation = '',
				lastAction = '';
			var GETSTATUS_TIMER = 15000;
			var previous_uris = '';
			//var selectedUri='',selectedItem={hapi:{baseline_state:"inventory_needed"}};
                        
            function getItem() {
                var uris = resource.getSelection().uris;
                selectedName = '';
		//getBaselineData request issued twice: To avoid this, storing baseline selected uris for the first time.
		//If the same uris coming for the second time,avoid getItem() call which intern calls getBaselineData
				if(uris === previous_uris)
				{
				  uris = '';
				  previous_uris= '';
				}
				else
				{
				  previous_uris = uris;
				}
                if (uris && uris.length > 0) {
					//if((uris[0] == selectedUri) && (selectedItem.hapi.baseline_state == "inventory_completed"))
						//return;
                    resource.getItem(uris/*resource.getSelection().uris[0]*/, {
                        success: function (item) {
                            selectedName = item.hapi.baseline_name;
							//if(selectedUri != item.hapi.baseline_uri)
                            dispatcher.fire("itemChange", item);
							//selectedItem = item;
							//selectedUri=item.hapi.baseline_uri;
                        },
                        error: function (errorMessage) {
                            dispatcher.fire("itemError", errorMessage);
                        }
                    });
                }
            }
            
            function getAssociations() {
                var uris = resource.getSelection().uris;
                if (uris && uris.length > 0) {
                    indexService.getParentAndChildrenAssociations({
                        uri: uris[0],
                        parentDepth: 1,
                        childDepth: 1,
                        handlers: {
                            success: function (tree) {
                                dispatcher.fire("associationsChange", tree);
                            },
                            error: function (errorMessage) {
                                dispatcher.fire("associationsError", errorMessage);
                            }}
                    });
                }
            }
	    
	    	function selectionChange(selection) {
                dispatcher.fire("selectionChange", selection);
                if (selection.uris) {
                    if (! selection.multiSelectId) {
                        // get the selected item
                        getItem();
                        //getAssociations();
                    } else {
                        // generate aggregate information
                        var aggregate = {count: selection.uris.length,
                            status:{ok: 0, warning: 0, error: 0, disabled: 0, unknown: 0}};
                        var indexResult;
                        
                        $.each(selection.uris, function(index, uri) {
                            indexResult = resource.getIndexResultForUri(uri);
                            aggregate.status[indexResult.status] += 1;
                        });
                        selectedName = aggregate.count + " servers";
                        
                        dispatcher.fire("aggregateChange", aggregate);
                    }
                }
            }
	    	
            function successAddBaseline(data, handlers) {
                
                //Adding a new baseline is success
                if (0 == data.hapi.hcode) {
                    if (data.hapi.hmessage.match(/This location already exists/i)) {
                        var errMsg = localizer.getString('hpsum.baseline.add.locationAlreadyExists') +"#" + data.hapi.command.output_data.uri;
                        handlers.error(errMsg);
                    } else {
                       //add a notification about successful operation
                       var notif = {
                        summary:data.hapi.hmessage,
                        sourceName: data.hapi.command.output_data.uri,
                        status: 'ok'
                        };
                       notifications.add(notif, true);
    				    //Perform inventory on location
                        var uri = "/Session/" + session.getToken()  + "/Baseline/location/" + data.hapi.command.output_data.location_id + "/inventory";
                        restapi.getURI(uri, {
                            success : function(data) {
                                //Started inventory on location successfully.
                                //We will wait for a while to complete the location inentory.
                                var timer = setInterval(function() {
                                        restapi.getURI(uri.replace("inventory", "getstatus"), {
                                            success : function(data) {
                                                if (data.hapi.location_state == "inventory_completed") {
                                                    resource.getIndexResults();
                                                    //Location inventory completed, will go back
                                                    clearInterval(timer);
                                                    restapi.getURI(uri.replace("inventory", "index"), {
                                                        success : function(data) {
                                                            data = data.hapi.output_data;
                                                         if (data.hasOwnProperty("baselines")) {
                                                            var baselines = [],
                                                                baselineURI;
                                                            baselines = data.baselines.baseline;
                                                            var baselineInfo = baselines[0];
                                                            if (baselineInfo != undefined && baselineInfo.hasOwnProperty("baseline_id")) {
                                                                baselineURI = baselineInfo.baseline_uri + '/getBaselineData';
                                                                resource.setSelectedUris([baselineURI]);
                                                                
                                                            }
                                                                resource.getIndexResults();
                                                                dispatcher.fire('itemChange', baselineInfo);
                                                                handlers.success({baseline_uri: baselineURI});
                                                            } else {
                                                                resource.getIndexResults();
                                                                handlers.success(data);
                                                            }
                                                        },
                                                        error : function(data) {
                                                            clearInterval(timer);
                                                            handlers.error(data.hapi.hmessage);
                                                        }
                                                    });
                                                }
                                            },
                                            error : function(data) {
                                                clearInterval(timer);
                                                handlers.error(data.hapi.hmessage);
                                            }
                                        });
                                    }, GETSTATUS_TIMER);   
                            },
                            error : function(data) {
                                handlers.error(data.hapi.hmessage);
                            }
                        });
                    }
                } else {
                    //Failed to add a new baseline
                    handlers.error(data.hapi);
                }
            }
			
	    	/**
             * Handles the success of the addBaseline command attempt by saving the
             * baseline information into indexservice.
             *
             * @param {{Baseline Details}}
             *            baselineDetails: The DTO from the server with
             *            the baseline ID and other information.
             * @param {{success:function():void,
             *            error:function(string):void}} handlers The
             *            caller's success and error handler functions.
             */
            function onaddBaselineSuccess(data, handlers) {
				
				if(data.hapi.hcode === 0)
				{
					//Start inventory for the location
					var uri = "/Session/" + session.getToken()  + "/Baseline/location/" + data.hapi.command.output_data.location_id + "/inventory";
					
					var inventoryHandlers = {
	                    						success : function(data, handlers) {
	                    							//update the master pane immediately
													resource.getIndexResults();
	                        						onInventorySuccess(data, handlers);
	                    		 				},
	                    						error : function(errorInfo, handlers) {
	                        						onInventoryError(errorInfo, handlers);
	                    						}
	                					};
					
					restapi.getURI(uri, inventoryHandlers);
					
					handlers.success(data);
	                
	                //add a notification about successful operation
	                notifications.add({
	                	summary: localizer.getString('hpsum.baseline.add.locationAdded'),
	                    sourceName: data.hapi.command.output_data.uri,
	                    status: 'ok'
	            	});
				}
				else
				{
					handlers.error(data.hapi.hmessage);
				}
			}
            
            function onInventorySuccess(data, handlers) 
            {
            	//handlers.success(data);
            }
            
            function onInventoryError(error, handlers) 
            {
            	//handlers.error(error);
            }
            
            function ongetBaselineError(error, handlers)
            {
            	handlers.error(error);
            }
            
            function ongetBaselineSuccess(data, handlers) {
            	
            	
	        	var i;
	        	//Create resources out of the data received as response
	        	for(i = 0; i < data.hapi.output_data.baselines.baseline.length; i += 1)
	        	{
	        		var item = {
	                    category: 'baseline',
	                    baselineId: data.hapi.output_data.baselines.baseline[i].baseline_id,
	                    name: data.hapi.output_data.baselines.baseline[i].baseline_name,
	                    location: data.hapi.output_data.baselines.baseline[i].baseline_url,
	                    uri: data.hapi.output_data.baselines.baseline[i].baseline_uri, //'/' + 'baseline' + '/item',
	                    status: data.hapi.output_data.baselines.baseline[i].baseline_state, //'ok',
	                    changing: 1,
	                    updatedAt: data.hapi.output_data.baselines.baseline[i].baseline_updated_at,
	                    stateDetails: '',
	                    index: baselines.length,
			    associated_node_count: data.hapi.output_data.baselines.baseline[i].nodes_using_baseline,
	                    attributes: {version: data.hapi.output_data.baselines.baseline[i].baseline_version, size: data.hapi.output_data.baselines.baseline[i].baseline_size}
	               	};
	        		
	        		baselines = baselines.concat(item);
	        	}
	        	
	        	iterator -= 1;
	        	
	        	if(iterator == 0)
	        	{
	        		handlers.success(baselines);
	        	}
            }

            /**
             * Handle an error coming back from the addBaseline request.
             *
             * @param {Object}
             *            errorInfo Error information from the server
             * @param {success:function():void,
             *            error:function(string):void
             *            }} handlers The
             *            caller's success and error handler functions.
             */
            function onaddBaselineError(errorInfo, handlers) {
                handlers.error(errorInfo);
            }
            
            function startInventorySuccess(data, handlers) 
            {
            	//if(data.hapi.message == "COMPLETE")
            	//{
            	//}
            	//handlers.success(data);
            }
            
            function startInventoryError(errorinfo, handlers)
            {
            	//handlers.error(errorinfo);
            }
            
            function indexLocations(handlers) {
            	
            	var baselineHandlers = {
	                    			success : function(data) {
	                        			ongetBaselineSuccess(data, handlers);
	                    		 	},
	                    			error : function(errorInfo) {
	                        			ongetBaselineError(errorInfo, handlers);
	                    			}
                					};
                    
                return {
                    success: function (data) {
                    	var i, uri;
                    	iterator = 0;
                    	baselines = [];
                    	//iterate through locations, call REST API for each location
                    	for(i = 0; i < data.hapi.output_data.baselines.baseline.length; i += 1)
                    	{
                    		var str = data.hapi.output_data.baselines.baseline[i].location_uri;
                    		str = str.replace(new RegExp(/\\/g),"/");
                    		var item = {
                    			location_id: data.hapi.output_data.baselines.baseline[i].locationid,
                    			location_uri: str,
                    			location_name: data.hapi.output_data.baselines.baseline[i].location_name
                    		};
                    		
                    		uri = '/session/'+ session.getToken() +'/Baseline/location/' + item.location_id + '/index';
                
                			iterator += 1;
               	 			restapi.getURI(uri, baselineHandlers);                    		
                    	}
                    	
                    	if(data.hapi.output_data.baselines.baseline.length == 0) {
                    		//return empty list if baselines list is empty
                    		handlers.success(baselines);
                    	}
                    },
                    error: handlers.error};
            }
            
            /**
             * @public
             */
            this.init = function() {
            	resource.setCompareResourcesFunction(indexResultsCompare);
				resource.on("selectionChange", selectionChange);
			};
            this.resource = function () {
                return resource;
            };
            
            this.getSelection = function() {
                return resource.getSelection();
            };
            
            this.selectionLabel = function () {
                return selectedName;
            };
            
            /**
             * @public
             * Add a listener for a specified event.
             * @param {string} eventName The name of the event.
             * @param {function(...)}
             */
            this.on = function(eventName, callback) {
            	var uris;
            	
                dispatcher.on(eventName, callback);
                
                // fire initial state
                switch (eventName) {
                    case 'selectionChange':
                        callback(resource.getSelection());
                        break;
                    case 'itemChange':
                    
                    	uris = resource.getSelection().uris;
                        if (uris && uris.length === 1) {
                        	resource.getItem(uris[0], {success: callback});
                        }
                        break;
                    case 'itemError':
                        uris = resource.getSelection().uris;
                        if (uris && uris.length === 1) {
                            resource.getItem(uris[0], {error: callback});
                        }
                        break;
                    case 'associationsChange':
                        getAssociations();
                        break;
                }
            };

            /**
             * @public
             * Remove a listener for a specified event.
             * @param {string} eventName The name of the event.
             * @param {function(...)} The function that was registered with "on"
             */
            this.off = function (eventName, callback) {
                dispatcher.off(eventName, callback);
            };
            
            this.getAddLink = function () {
                var result = null;
                if (session.canPerformAction('BASELINE', 'ADD')) {
                    result = linkTargetBuilder.makeLink(localizer.getString('hpsum.baseline.add.title'), null, 'add', 'baseline', 'ADD');
                }
                return result;
            };
            
            this.getAllBaselines = function (handlers) {
                
                iterator = 0;
                baselines = [];
                var localHandlers = {
	                    			success : function(data) {
	                        			ongetLocationSuccess(data, handlers);
	                    		 	},
	                    			error : function(errorInfo) {
	                        			ongetLocationError(errorInfo, handlers);
	                    			}
                			};
                			
               	restapi.getURI('/Session/' + session.getToken() + '/Baseline/location/index', indexLocations(handlers));
               
            };
			 
            
			this.getBaselines = function(handlers) {
					var uri = '/Session/' + session.getToken() + '/baseline/location/index?indexChilds=Yes';
					restapi.getURI(uri, {
						success : function(data) {
							var locations = [];
							baselines = [];
							locations = data.hapi.output_data.locations.location;
							
							for (var idx = 0; idx < locations.length; idx++) {
								//get list of baselines which are inventory completed and dont include baselines that are still in inventory
								var baselines_invcompl = $.grep(locations[idx].baselines.baseline, function(baseline, index) {
						                            return (
						                            	(baseline.baseline_state == "inventory_completed") 
						                            	);
								});
								if(baselines_invcompl && baselines_invcompl.length > 0)
									baselines = baselines.concat(baselines_invcompl);
							}
							handlers.success(baselines);
						},
						error : function(msg) {
							handlers.error(msg);
						}
					});
			};
			
			this.getGUBaselines = function(handlers) {
					var uri = '/Session/' + session.getToken() + '/baseline/location/index?indexChilds=Yes';
					restapi.getURI(uri, {
						success : function(data) {
							var locations = [];
							baselines = [];
							locations = data.hapi.output_data.locations.location;
							for (var idx = 0; idx < locations.length; idx++) {
								//get list of baselines which are inventory completed and dont include baselines that are still in inventory
								var baselines_invcompl = $.grep(locations[idx].baselines.baseline, function(baseline, index) {
						                            return (baseline);
								});
								if(baselines_invcompl && baselines_invcompl.length > 0)
									baselines = baselines.concat(baselines_invcompl);
							}
							handlers.success(baselines);
						},
						error : function(msg) {
							handlers.error(msg);
						}
					});
			};
			
			this.getListofPFWBundles = function(parameter, handlers) {
					var uri = '/Session/' + session.getToken() + '/baseline/getPFWBundleList';
					restapi.postObject(uri, parameter, "",{
					//restapi.getURI(uri, {
						success : function(data) {
							if(data.hapi.hcode != 0)
								handlers.error(data.hapi.hmessage);
							else {	
							var locations = [];
							baselines = [];
							locations = data.hapi.bundles.product;
							
							for (var idx = 0; idx < locations.length; idx++) {
								baselines = baselines.concat(locations[idx]);
							}
							handlers.success(baselines,data.hapi.validated_token_id);
							}
						},
						error : function(msg) {
							handlers.error(msg);
						}
					});
				
			};

            this.getPFWReciepefile = function(input, handlers) {
                    var uri = '/Session/' + session.getToken() + '/baseline/getpfwreciepefile';
                    restapi.postObject(uri, input, "",{
                        success : function(data) {
                            if (handlers) {
                                handlers.success(data);
                            }
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    });
            };
            
			this.exportCompConfig = function(configData, handlers) {
                    var uri = '/Session/' + session.getToken() + '/baseline/exportCompConfig';
                    restapi.postObject(uri, configData, "",{
                        success : function(data) {
							var isExportSuccess = data.hapi.baselines.baseline[0].components.component.isExportSuccess;
                            if (!isExportSuccess) 
							{
                                handlers.error(data);
                            }
							else{
                                handlers.success(data);
                            }
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    });
            };
			
			this.importCompConfig = function(configData, handlers) {
                    var uri = '/Session/' + session.getToken() + '/baseline/importCompConfig';
                    restapi.postObject(uri, configData, "",{
                        success : function(data) {
						var isImportSuccess = data.hapi.baselines.baseline[0].components.component.isImportSuccess;
                            if (!isImportSuccess)  
							{
                                handlers.error(data);
                            }
							else{
                                handlers.success(data);
                            }
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    });
            };
			
			this.getBaselinesAll = function(handlers) {
					var uri = '/Session/' + session.getToken() + '/baseline/location/index?indexChilds=Yes';
					restapi.getURI(uri, {
						success : function(data) {
							var locations = [];
							locations = data.hapi.output_data.locations.location;
							handlers.success(locations);
						},
						error : function(msg) {
							handlers.error(msg);
						}
					});
			};
			
			this.getSourceHPSUMVersion = function(inputPath, handlers) {
                    var uri = '/Session/' + session.getToken() + '/baseline/getsourcehpsumversion';
                    restapi.postObject(uri, inputPath, "",{
                        success : function(data) {
							handlers.success(data);
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    });
            };
			
            /**
             * @public
             * Add a new baseline item into IndexService
             * @param {item} item that need to be added into indexservice
             * @param {handlers(...)} The function that was registered with "on"
             */
            this.addItem = function (item, handlers) {
		var workingLoc;
		var unc_uname, unc_passwd;
		// In case of local baseline the working location will
		// be set automatically by the engine. only in case of
		// FTP we need to set the working location	
                if(item.locationType == "local")
                {
                    item.uripath = item.location;
                }
                if(item.locationType == "FTP" || item.locationType == "HTTP")
                {
                   // item.uripath = 'PFW';
                    workingLoc = item.location;
                }
				if(item.locationType == "UNC")
                {
					if(item.usecurrcreds)
					{ 
						unc_uname = 0;
						unc_passwd = 0;
					}
					else 
					{
						unc_uname = item.username;
						unc_passwd = item.password;
					}
				}

                

                var input = {
                                 hapi: { 
                                            uri: item.uripath,
                                            username:item.username,
                                            password:item.password,
											unc_username:unc_uname,
											unc_password:unc_passwd,
                                            working_location:workingLoc,
                                            locationtype: item.locationType ,                                    
                                            proxy_settings: item.proxy_settings,
											filter_os : item.filter_os    	
                                        }
                            };
				restapi.postObject("Session/" + session.getToken() + "/Baseline/add", 
								    input,  "", 
            		         {
                    			success : function(baselineDetails) {
                        			//onaddBaselineSuccess(baselineDetails, handlers);
                        			successAddBaseline(baselineDetails, handlers);
                    		 	},
                    			error : function(errorInfo) {
                        			onaddBaselineError(errorInfo, handlers);
                    			}
                			}, {});
					
				//Mockup data to simulate adding new baseline into IndexService		 
				/*
                item.status = 'unknown';
				indexService.addItem('baseline', item);
                handlers.success("");
                notifications.add({
                	summary: localizer.getString('hpsum.baseline.add.baselineAdded'),
                    sourceName: item.name,
                    status: 'ok'
            	});
				*/
            };
            
            /**
             * @public
             * Craete a new custom baseline
             * @param {item} item that need to be used to create custom baseline
             * @param {handlers(...)} The function that was registered with "on"
             */
            this.createCustomBaseline = function (item, handlers) {
			
				restapi.postObject("Session/" + session.getToken() + "/Baseline/createbundle", 
								item,  "", 
            		         {
                    			success : function(baselineDetails) {
                        			onaddBaselineSuccess(baselineDetails, handlers);
                    		 	},
                    			error : function(errorInfo) {
                        			onaddBaselineError(errorInfo, handlers);
                    			}
                			}, {});
			};
			
			function indexResultsCompare(last, latest){
				//Check if path has changed from last time.
                var loc = router.location().split('/');
                if((loc.length < 6) && (loc[2] == 'show'))
                    return false;
                var location = loc[1];
                var action = loc[2];
                                    
                if(lastLocation != location || lastAction != action) {
                    lastLocation = location;
                    lastAction = action;
                    return false;
                }
                
				if(last.location != latest.location)
					return false;
				if(last.id != latest.id)
					return false;
                if((last.state == latest.state))
           			return true;
            	return false;
            }
			
			/**
             * @public
             * Get custom baseline creation status
             * @param {item} This is response of createbundle command. This response has resource_id for the newly creating custom baseline
             * @param {handlers(...)} The function that was registered with "on"
             */
			this.getCustomBaselineStatus = function (item, handlers) {
				
            	var uri = "Session/" + session.getToken() + "/baseline/" + item.hapi.command.output_data.resource_id + "/getstatus";
            	var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};
            	restapi.getURI(uri, thishandlers);	
            };
			/**
			* Get the Session Status. This is required to know the number of Custom Baselines
			* in progress. 
			* This will return the customBaselineProcessesSupported and customBaselineProcessesInProgress
			*/
			this.getCBStatus = function (item, handlers) {
				var uri = "Session/" + session.getToken() + "/getstatus";
				var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};
            	restapi.getURI(uri, thishandlers);
            };
			
            this.startInventory = function (item, handlers) {
            	var uri = item.uri.replace('getBaselineData','inventory');
            	
            	restapi.getURI(uri, {
                    			success : function(data) {
                    				if (handlers) {
                        				handlers.success(data);
                        			}
                    		 	},
                    			error : function(errorInfo) {
                    				if (handlers) {                   
                        				handlers.error(errorInfo);
                        		}
                    			}
                    	});
            };
            
            this.startBundleValidation = function (item, handlers) {
            	restapi.getURI(item, {
            			success : function(data) {
                    				if (handlers) {
                        				handlers.success(data);
                        			}
                    		 	},
                    			error : function(errorInfo) {
                    				if (handlers) {                   
                        				handlers.error(errorInfo);
                        		}
                    			}
                    	});
            };
            
            // This function saves the given reciepe file.
	    // input contains the path of matrixConfig.xml
            this.saveReciepeFile = function (input, handlers) {
            	var uri = "Session/" + session.getToken() + "/Baseline/savereciepefile";
            	restapi.postObject(uri, 
								input,  "", 
            		         {
                    			success : function(data) {
                    				if (handlers) {
                        				handlers.success(data);
                        			}
                        			
                    		 	},
                    			error : function(errorInfo) {
                    				if (handlers) {                   
                        				handlers.error(errorInfo);
                        			}                        			
                    			}
                			}, {});
            	
            };
            
            this.validateReciepeFile = function(uri, input, handlers) {
            	
            	restapi.postObject(uri, 
								input,  "", 
            		         {
                    			success : function(data) {
                    				if (handlers) {
                        				handlers.success(data);
                        			}
                        			
                    		 	},
                    			error : function(errorInfo) {
                    				if (handlers) {                   
                        				handlers.error(errorInfo);
                        			}                        			
                    			}
                			}, {});            	
            };
            
            // Sends the inventory command for the PFW bundles
            // with the schedule information.
            this.startPFWInventory = function (item, handlers) {
            	var uri;
            	uri = item.uri + '/inventory';
            	var isscheduled = "yes";
            	if (item.scheduled == 'Off')
            		isscheduled = "no";
            	var input = {
                                 hapi: {                                          
                                         scheduled: isscheduled ,
                                         schedule_information : { 
                                                                date : item.scheduleDate , 
                                                                time : item.scheduleTime , 
                                                                scheduletype : item.scheduleType , 
                                                                recurs_every: item.scheduleRecurs 
                                                            }
                                        }
                            };
                            
                restapi.postObject(uri, 
								input,  "", 
            		         {
                    			success : function(data) {
                        			startInventorySuccess(data, handlers);
                    		 	},
                    			error : function(errorInfo) {
                        			startInventoryError(errorInfo, handlers);
                    			}
                			}, {});            	
            };
            
            this.getComponentData = function (item, handlers) {
            	var uri = "Session/" + session.getToken() + "/Baseline/location/" + item.location_id + "/bundle/" + item.baseline_id + "/getComponentData";
            	var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};
            	//restapi.getURI(uri, handlers);
            	
            	var payload = { hapi: { component_id: item.component_id,
					filter: item.filter
					 }
				};
				if(item.filter == undefined)
					delete payload['filter'];
            	
            	restapi.postObject(uri, payload
								,  "", thishandlers, {});

            };
			this.getHardwareInfo = function (item,handlers){
			//var uri = "Session/" + session.getToken() + "/Baseline/location/" + item.location_id + "/bundle/" + item.baseline_id + "/gethwinfo";
			var uri = "Session/" + session.getToken() + "/Baseline/location/" + item.location_id + "/bundle/" + item.baseline_id + "/gethwcompinfo";
			var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};
			
				restapi.getURI(uri, thishandlers);			
			};
            
            this.getBaselineStatus = function (item, handlers) {
            	var uri = "Session/" + session.getToken() + "/Baseline/location/" + item.location_id + "/bundle/" + item.baseline_id + "/getstatus";
            	var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};
            	restapi.getURI(uri, thishandlers);
            };
            
            this.getBundleIndexData = function (item, handlers) {
            	var uri = "Session/" + session.getToken() + "/Baseline/location/" + item.location_id + "/bundle/" + item.baseline_id + "/index";
            	var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};
            	restapi.getURI(uri, thishandlers);
            };
			this.getCompConfDetail = function (item, handlers) {
            	var uri = "Session/" + session.getToken() + "/Baseline/location/" + item.location_id + "/bundle/" + item.baseline_id + "/getcomponentconfigdata";
            	var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};
            	//restapi.getURI(uri, handlers);
            
            	restapi.postObject(uri, 
								{
								 hapi: { component_id: item.component_id }
								},  "", thishandlers, {});
            };
			this.saveComponentConfig = function (item, compdata, handlers) {
				var uri = "Session/" + session.getToken() + "/Baseline/location/" + item.location_id + "/bundle/" + item.baseline_id + "/savecomponentconfigdata";
				var thishandlers =	{
                    			success : function(data) {
									handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
							};
				restapi.postObject(uri, compdata, "", thishandlers, {});
			};
			
            this.removeBaseline = function (item, handlers) {
                var uri = "Session/" + session.getToken() + "/Baseline/location/" + item.location_id + "/bundle/" + item.baseline_id + "/remove";
                var thishandlers = {
                    success : function(data) {
                        if(data.hapi.hcode == 0) {
                            resource.clearAllSelectedUris();
                            handlers.success("");
                            notifications.add({
                                summary: localizer.getString("hpsum.baseline.add.deletedBaseline"),
                                sourceName: item.baseline_url,
                                status: 'ok'
                            });
                            resource.clearAllSelectedUris();
                            resource.getIndexResults();
                            router.go(urlFragment.replaceUris(router.location(), []), 'hpsum deleted baseline');
                            dispatcher.fire("selectionChange", []);
                            handlers.success(data);
                        }
                        else if(data.hapi.hcode == 3008){
                            //Baseline is associated with a node, confirm the user wants to delete. If yes, send remove with force option
                            var text = data.hapi.hmessage.replace(/,/g, '<br>');
                            text = text.replace(/:/g, '<br><br>');
                            text = text + "<li>" + localizer.getString("hpsum.node.assignNewBaseline") + "</li>" + "<li>" + localizer.getString("hpsum.node.deleteNodes") + "</li>";
                            $("<div></div>").dialog( {
				 open : function(event,ui) {
						$(this).css({'max-height':200, 'overflow-y':'scroll'});
			},
                                buttons: { "Ok": function () {                                                    
                                                    $(this).dialog("close");
                                                    handlers.success(data); 
                                                }                                           
                                         },
                                    close: function (event, ui) { $(this).remove(); handlers.success(data);},
                                    resizable: false,
                                    title: localizer.getString("hpsum.baseline.add.deleteBaseline"),
                                    modal: true
                                }).html(text);
								handlers.error(data);
                        }
						else if(data.hapi.hcode == 3016){
							handlers.success(data);
						}
                    },
                    error : function(errorInfo) {
                        handlers.error(errorInfo);
                    }
                };
                restapi.postObject(uri,"", "", thishandlers, {});
				//resource.clearAllSelectedUris();
				//resource.getIndexResults();
            };

            this.abortBaseline = function (item, handlers) {
                var uri = "Session/" + session.getToken() + "/Baseline/location/" + item.location_id + "/bundle/" + item.baseline_id + "/abort";
                var thishandlers = {
                    success : function(data) {
                        if(data.hapi.hcode == 0) {
                            resource.clearAllSelectedUris();
                            handlers.success("");
                            notifications.add({
                                summary: localizer.getString("hpsum.baseline.add.abortedBaseline"),
                                sourceName: item.baseline_url,
                                status: 'ok'
                            });
                            resource.getIndexResults();
                            router.go(urlFragment.replaceUris(router.location(), []), 'hpsum aborted baseline');
                            dispatcher.fire("selectionChange", []);
                            handlers.success(data);
                        }
                        else{
                            handlers.error(data);
                        }
                    },
                    error : function(errorInfo) {
                        handlers.error(errorInfo);
                    }
                };
                restapi.postObject(uri,"", "", thishandlers, {});
                resource.clearAllSelectedUris();
                resource.getIndexResults();
            };
			
			this.getAssociatedNodes = function (item, handlers) {
                var uri = "Session/" + session.getToken() + "/Baseline/location/" + item.location_id + "/bundle/" + item.baseline_id + "/getassociatednodes";
                var thishandlers = {
                    success : function(data) {
                        if(data.hapi.hcode == 0) {
                            handlers.success(data);
                        }
                        else {
								handlers.error(data);
                        }
                    },
                    error : function(errorInfo) {
                        handlers.error(errorInfo);
                    }
                };
                restapi.postObject(uri,"", "", thishandlers, {});
            };
            
            /**
             * @public
             * Get components with their supported OS list
             * @param {item} This is baseline uri
             * @param {handlers(...)} The function that was registered with "on"
             */
			this.getosname = function (baseline_uri, handlers) {
				
            	var uri = baseline_uri + "/getosname";
            	var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};
            	restapi.getURI(uri, thishandlers);
            };
            
            /**
             * @public
             * Get components with their supported device list
             * @param {item} This is baseline uri
             * @param {handlers(...)} The function that was registered with "on"
             */
			this.getsupporteddevice = function (baseline_uri, handlers) {
				
            	var uri = "Session/" + session.getToken() + baseline_uri + "/getsupporteddevice";
            	var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};
            	restapi.getURI(uri, thishandlers);
            };
            
           this.getComponents = function (baseline_uri, handlers) {		
            	var uri = baseline_uri + "/getComponents";
            	var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};
            	restapi.getURI(uri, thishandlers);
            };
            
            this.getEnhancements = function (baseline_uri, handlers) {		
            	var uri = baseline_uri + "/getEnhancements";
            	var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};
            	restapi.getURI(uri, thishandlers);
            };
            
            this.getOsInfo = function (baseline_uri, handlers) {		
            	var uri = baseline_uri + "/getOsInfo";
            	var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};
            	restapi.getURI(uri, thishandlers);
            };
            this.getCategoryInfo = function (baseline_uri, handlers) {      
                var uri = baseline_uri + "/getCategoryInfo";
                var thishandlers =  {
                                success : function(data) {
                                    handlers.success(data);
                                },
                                error : function(errorInfo) {
                                    handlers.error(errorInfo);
                                }
                            };
                restapi.getURI(uri, thishandlers);
            };  
            
            this.addDefaultBaseline = function (item, handlers) {
            	var workingLoc;
				
		        if(item.locationType == "local")
                {
                    item.uripath = item.location;
                }
                
                var input = {
                     hapi: { 
                        uri: item.uripath,
                        username:item.username,
                        password:item.password,
						unc_username:item.unc_uname,
						unc_password:item.unc_passwd,
                        working_location:workingLoc,
                        locationtype: item.locationType ,                                    
                        proxy_settings: item.proxy_settings 
                     }
                };
                
				restapi.postObject("Session/" + session.getToken() + "/Baseline/add", input,  "", 
    		         {
            			success : function(baselineDetails) {
            				//add a notification about successful operation
	                    	var notif = {
	                        	summary:baselineDetails.hapi.hmessage,
	                        	sourceName: baselineDetails.hapi.command.output_data.uri,
	                        	status: 'ok'
	                        };
	                    	notifications.add(notif, true);
                			handlers.success(baselineDetails);
            		 	},
            			error : function(errorInfo) {
                			handlers.error(errorInfo);
            			}
        			}, {});
            }; //addDefaultBaseline
			this.getAttributes = function(handlers){
					var uri = '/session/' + session.getToken() + '/getattributes';
					restapi.getURI(uri, handlers);
				};
			this.setAttributes = function(input,handlers){
                    var uri = '/session/' + session.getToken() + '/setattributes';
                    restapi.postObject(uri,input, "", handlers);
                };
                	
			this.retryPFW=function(input,baseline,handlers){
				var base=baseline.split("/");
				var location_id=base[0];
				var baseline_id=base[1];
				var uri = "session/" + session.getToken() + "/Baseline/location/" + location_id + "/bundle/" + baseline_id + "/retryPFW";
            var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};				
				restapi.postObject(uri, input, "",thishandlers);
				};
				
			this.revalidate=function(input,baseline,handlers)
			{
				var base=baseline.split("/");
				var location_id=base[0];
				var baseline_id=base[1];
				var uri = "session/" + session.getToken() + "/Baseline/location/" + location_id + "/bundle/" + baseline_id + "/revalidate";
            var thishandlers =	{
                    			success : function(data) {
                        			handlers.success(data);
                    		 	},
                    			error : function(errorInfo) {
                        			handlers.error(errorInfo);
                    			}
                			};				
				restapi.postObject(uri, input, "",thishandlers);
				};
			
            /*
             * Initiate location inventory and starts inventory for all the bundles in the location.
             * Uses location/getstatus, location/index and finally starts inventory for all child bundles
             * based on inventory_state attribute
             */
            this.inventoryDefaultBaseline = function (data, handlers) {
				var isBundleInvProgress = false;
				var location_id = data.hapi.command.output_data.location_id;
                //check whether any bundle under the location inventory is going on and then perform inventory on the location
				var uri = "/Session/" + session.getToken()  + "/Baseline/location/" + location_id + "/index";
				restapi.getURI(uri, {
					success : function(data) {
						data = data.hapi.output_data;
						if (data.hasOwnProperty("baselines")) {
							var baselines = [];
							baselines = data.baselines.baseline;
							//Check the state of the baselines and set the isBundleInvProgress flag to true.
							for(var ind=0; ind < baselines.length; ind++) {
								var baselineInfo = baselines[ind];
								if (baselineInfo != undefined && baselineInfo.hasOwnProperty("baseline_uri") && baselineInfo.baseline_state != 'inventory_completed') {
									isBundleInvProgress = true;
								}
							}
						}
						if(!isBundleInvProgress) 
						{
							//Perform inventory on location when no bundles in the location are not in inventory in progress state
							uri = "/Session/" + session.getToken()  + "/Baseline/location/" + location_id + "/inventory";
							restapi.getURI(uri, {
								success : function(data) {
									//Started inventory on location successfully.
									//We will wait for a while to complete the location inentory.
									var timer = setInterval(function() {
										restapi.getURI(uri.replace("inventory", "getstatus"), {
											success : function(data) {
												if (data.hapi.location_state == "inventory_completed") {
													//Location inventory completed, call index to get bundle info
													clearInterval(timer);
													restapi.getURI(uri.replace("inventory", "index"), {
														success : function(data) {
															data = data.hapi.output_data;
															if (data.hasOwnProperty("baselines")) {
																var baselines = [];
																baselines = data.baselines.baseline;
																//start inventory for all baselines in the location
																for(var ind=0; ind < baselines.length; ind++) {
																	var baselineInfo = baselines[ind];
																	if (baselineInfo != undefined && baselineInfo.hasOwnProperty("baseline_uri") && baselineInfo.baseline_state == 'inventory_needed') {
																		var baselineURI = '';
																		baselineURI = baselineInfo.baseline_uri + '/inventory';
																		if(baselineURI.length > 0) {
																			//start inventory for the bundle
																			restapi.getURI(baselineURI, {
																				success : function(data) {
																				},
																				error : function(errormsg){
																				}
																			});
																		}
																	}	
																}
																handlers.success('Baseline inventory started.');
															} else {
																handlers.success('No Baseline available in the default location.');
															}
														},
														error : function(data) {
															clearInterval(timer);
															handlers.error(data.hapi.hmessage);
														}
													});
												}
											},
											error : function(data) {
												clearInterval(timer);
												handlers.error(data.hapi.hmessage);
											}
										});
									}, GETSTATUS_TIMER);   
								},
								error : function(data) {
									handlers.error(data.hapi.hmessage);
								}
							}); //inventoryDefaultBaseline
						}
					},
					error : function(data) {
					}
				});
            };
            
            /*
             * This REST API used to create new directory from 'Browse' dialog.
             * We use 'browse' REST call to create new directory
             * The target location and new directory name is specified in input.
             * The handlers are used to process response if required. 
             */
            this.createDirectory = function(input, handlers) {
                    var uri = "Session/" + session.getToken()  + "/Baseline/browse";
                    restapi.postObject(uri, input, "",{
                        success : function(data) {
                            if (handlers) {
                                handlers.success(data);
                            }
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    });
            };

}
        return new BaselinePresenter();
	
    }());
    return  BaselinePresenter;


});
