// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type {ServerPresenter}
 */
define(['hpsum/model/node/NodeResource',
    'hpsum/presenter/baseline/BaselinePresenter',
    'hp/services/IndexService',
    'hp/services/IndexFilter',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/core/LinkTargetBuilder',
    'hp/core/Notifications',
    'hp/core/EventDispatcher',
    'hp/services/REST',
    'hp/model/Session',
    'hp/core/Localizer'], 
function (resource, baselinePresenter, indexService, IndexFilter, router, urlFragment, linkTargetBuilder,
    notifications, EventDispatcher,restService, session, localizer) {
"use strict";

    
    var NodePresenter = ( function() {

            /**
             * @constructor
             */
            function NodePresenter() {

                var dispatcher = new EventDispatcher(),
                 baselines = [],
                 types = [],
                 selectedName = '',
                 selectedItem = '',
                 lastLocation = '',
                 lastAction = '',
                 trackUri = null,
                 initDone = false,
                 aggregate = null,
                 itemchange = null,
                 allBaselines = null,
		 nodesAdvOptions = [];
                var tMap={};
                var i=0;
                var installsets = [];
                var iloTasklistlength = 0;
                var iloTasklistArr = [];
                var task = {
                    category : 'task',
                    name : localizer.getString('hpsum.common.adding'),
                    uri : '/task/task-' + (new Date()).getTime(),
                    status : 'unknown',
                    changing : true,
                    sourceUri : null,
                    sourceName : null,
                    date : null,
                    state : 'running',
                    progress : 10,
                    progressStep : 'Initializing',
                    owner : session.getUser()
                };

                function getItem() {
                    var uris = resource.getSelection().uris;
                    selectedName = '';
                    if (uris && uris.length > 0) {
                        resource.getItem(uris[0], {
                            //resource.getItem(resource.getSelection().uris[0], {
                            success : function(item) {
                                selectedName = item.name;
                                selectedItem = item;
                                var index = $.inArray(item.hapi.type, types);
                                if (index === -1)
                                    types.push(item.hapi.type);
                                dispatcher.fire("itemChange", item);
                            },
                            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) {
                    
                aggregate = null;
                    if (selection.uris) {
                        if (!selection.multiSelectId) {
                            // get the selected item
                            getItem();
                            //getAssociations();
                        } else {
                            // generate aggregate information
                            aggregate = {count: selection.uris.length,
                            //status:{ok: 0, warning: 0, error: 0, disabled: 0, unknown: 0},
                            node_name:{ },
                            node_phase:{ },
                            node_type:{ },
                            node_status:{ },
                            node_state:{ },
                            node_id:{ }};
                            var indexResult;
                        var i=0;
                        $.each(selection.uris, function(index, uri) {
                            indexResult = resource.getIndexResultForUri(uri);
                            if(indexResult){
                                var nodeId = uri.split("/");
                                aggregate.node_id[i] = nodeId[4];
                                aggregate.node_phase[i] = indexResult.node_phase;
                                aggregate.node_type[i] = indexResult.type;
                                aggregate.node_state[i] = indexResult.node_state;
                                aggregate.node_status[i] = indexResult.node_status;
                                aggregate.node_name[i] = indexResult.name;
                                i++;
                            }
                        });
                        selectedName = aggregate.count + " servers";
                        
                        dispatcher.fire("aggregateChange", aggregate);
                    }
                }
            }
            
            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;
                }
				/*This check is for the sort functionality on the Master pane. This function returns false to the
				  bubble sort, if the current node is already sorted w.r.t the previous one */
				if(last.name != latest.name)
				{
					return false;
				}
                if((last.node_state == latest.node_state) && (last.node_phase == latest.node_phase)
                    && (last.node_status  == latest.node_status))
				{
                    return true;
				}
                return false;
            }
            
            
            function onAddSuccess(data,message)
            {
                task.name = localizer.getString('hpsum.switchUI.added');
                task.status = 'ok';
                        
                var notif = {
                    summary: task.name,
                    status: task.status,
                    sourceName: task.sourceName,
                    sourceUri: task.sourceUri,
                    progress: task.progress,
                    step: task.progressStep
                };

                var summary = data.hapi.hmessage;
				// generate activity message.
                if(message != "" && message != undefined)
                {
				   if(data.hapi.hasOwnProperty("nodes") && data.hapi.nodes.hasOwnProperty("node"))
                    {		
						 var len = data.hapi.nodes.node.length;
						 var addedNodesCount = 0;
						 var addedNodeIndex = 0; // this will be used to assign date value to the first node added.
						 task.sourceName = "";
						 for(var nodeDataCount = 0; nodeDataCount < len ; nodeDataCount++)
						 {
							if(!data.hapi.nodes.node[nodeDataCount].exists){
								addedNodesCount++;
								if(addedNodesCount == 1)
								{
									addedNodeIndex = nodeDataCount;
									task.sourceName = data.hapi.nodes.node[nodeDataCount].ip;
								}
								else
								{
									task.sourceName = task.sourceName + "," + data.hapi.nodes.node[nodeDataCount].ip;
								}
							}
						 }
						message = task.sourceName + localizer.getString('hpsum.node.nodesAddedSuccessfully');
						
						//add date details to the first node added. 
						if(!data.hapi.nodes.node[0].exists){
							task.sourceUri = data.hapi.nodes.node[0].uri;
							task.date = data.hapi.nodes.node[0].date;
							data.hapi.nodes.node[0].status = 'unknown';
						}
						else
						{
							task.sourceUri = data.hapi.nodes.node[addedNodeIndex].uri;
							task.date = data.hapi.nodes.node[addedNodeIndex].date;
							data.hapi.nodes.node[addedNodeIndex].status = 'unknown';
						}
					}					
                   summary = message;
                    
                }
				else
				{
					if(task.sourceName != "" && task.sourceName != undefined)
					{
						summary = task.sourceName + localizer.getString('hpsum.node.nodesAddedSuccessfully');
					}
				}

                notif.summary = summary;
                notif.status = task.status;
                notifications.add(notif, true);
                        
                if (task.sourceUri === trackUri) {
                    dispatcher.fire('notificationChange', notif);
                }
                
            }
            
            function onAddError(){
                
            }
			
			function onNodeStatusSuccess(data){
            	 	if(!data.hapi.node_status.node_phase.match(/initialize/i)){
        				clearInterval(tMap[data.hapi.node_status.node_id]);
        				resource.getIndexResults();
						delete tMap[data.hapi.node_status.node_id];
        			}
        		}   
            function onNodeStatusError(){
            	
            }
            
            this.fireAggregate = function()
            {
                dispatcher.fire("aggregateChange", aggregate);
            };
			
			this.startNodeStatus = function(item){
				if(tMap[item.node_id])
            			return;
        		   	tMap[item.node_id] = setInterval(function () {
						var uri = '/session/' + session.getToken() + '/node/' + item.node_id + '/getstatus';
                    var thishandlers = {
                        success : function(data) {
                           onNodeStatusSuccess(data);
                        },
                        error : function(errorInfo) {
                            onNodeStatusError(errorInfo);
                        }
                    };
                    restService.getURI(uri, thishandlers);
                			
                }, 3000);
            };

            this.fireItemChange = function()
            {
                dispatcher.fire("itemChange", itemchange);
            };

                this.otheroption = function(item, handlers) {

                    var sessionurl = '/Session/' + session.getToken() + '/node/' + item.node_id + '/getattributes';
                    restService.getURI(sessionurl, handlers);

                };

                this.getTaskQuequeList = function (item, handlers) {
                    var taskQueueURI = '/Session/' + session.getToken() + '/node/' + item.node_id + "/getilotaskqueue";
                    restService.getURI(taskQueueURI, handlers);
                };

                this.getInstallSets = function (item, handlers)
                {
                    var installsetURI = '/Session/' + session.getToken() + '/node/' + item.node_id + "/iloinstallset/index";
                    restService.getURI(installsetURI, handlers);
                };

                this.getInstallSetDetails = function (item, handlers) {
                    var installsetURI = '/Session/' + session.getToken() + '/node/' + item.node_id + "/iloinstallset/" + item.installset_id + "/getdata";
                    restService.getURI(installsetURI, handlers);
                };
				
				this.getInstallSetStatus = function (item, handlers) {
                    var installsetURI = '/Session/' + session.getToken() + '/node/' + item.node_id + "/iloinstallset/" + item.installset_id + "/getstatus";
                    restService.getURI(installsetURI, handlers);
                };
				
				this.removeInstallSetItem = function (item, handlers) {
                    var installsetURI = '/Session/' + session.getToken() + '/node/' + item.node_id + "/iloinstallset/" + item.installset_id + "/remove";
                    restService.postObject(installsetURI, null, {
						success : function(data) {
							if (data.hapi.hcode == 0) {
								handlers.success(data,item);
							} else {
								handlers.error(data.hapi.hmessage);
							}
						},
						error : function(data) {
							handlers.error(data,item);
						}
					}, null);
                };
				
				this.clearInstallSetItem = function(item, handlers) {
					var installsetURI = '/Session/' + session.getToken() + '/node/' + item.node_id + "/iloinstallset/" + item.installset_id + "/clear";
					restService.postObject(installsetURI, null, {
						success : function(data) {
							if (data.hapi.hcode == 0) {
								handlers.success(data,item);
							} else {
								handlers.error(data.hapi.hmessage);
							}
						},
						error : function(data) {
							handlers.error(data,item);
						}
					}, null);
			};

                this.getbaseline = function(item, handlers) {
                    var sessionurl = '/Session/' + session.getToken() + '/node/' + item.node_id + '/getupdatelist';
                    if(item.type =="ilo_federation")
                        sessionurl = '/Session/' + session.getToken() + '/node/scalableupdate' + item.node_id + '/getupdatelist';
                    restService.getURI(sessionurl, handlers);

                };

                this.deploy = function(item, handlers) {
                    var uri = '/Session/' + session.getToken() + '/node/' + item.node_id + '/deploy';
                    var scheduledDateTime = item.hasOwnProperty('set_schedule_date_time') ? item.set_schedule_date_time : "";
					var cleanuponexit = item.hasOwnProperty('cleanup_onexit') ? item.cleanup_onexit : false;
					var cleanupallonexit = item.hasOwnProperty('cleanupall_onexit') ? item.cleanupall_onexit : false;
					var stageOnly = item.hasOwnProperty('stage_only') ? item.stage_only : false;
					
					var object = {
                        hapi : {
                            schedule_date_time : scheduledDateTime,
							cleanupall_onexit : cleanupallonexit,
							cleanup_onexit: cleanuponexit,
							stage_only: stageOnly
                        }
                    };
                    restService.postObject(uri, object, {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                                resource.getIndexResults();
                            } else
                                handlers.error(data.hapi.hmessage);
                        },
                        error : function() {
                            handlers.error()
                        }
                    } , null );
                };

                this.setattribute = function(item, optiondetails, handlers) {
                    var uri = '/Session/' + session.getToken() + '/node/' + item.node_id + '/setattributes';
                    restService.postObject(uri, optiondetails, "", handlers, {});
                };
				
				this.getDeviceInfo = function(item, optiondetails, handlers) {
                    var uri = '/Session/' + session.getToken() + '/node/' + item.node_id + '/getDeviceInfo';
                    restService.postObject(uri, optiondetails, "", handlers, {});
                };
				
				this.setDeviceInfo = function(item, optiondetails, handlers) {
                    var uri = '/Session/' + session.getToken() + '/node/' + item.node_id + '/setDeviceInfo';
                    restService.postObject(uri, optiondetails, "", handlers, {});
                };
            this.setattributemulti = function (node_id,optiondetails,handlers){
             var uri = '/Session/'+session.getToken()+'/node/'+node_id +'/setattributes';           
                restService.postObject(uri, optiondetails,"",handlers, {});             
            };

                this.activate = function(item, activateOptions, handlers) {
                    var uri = '/Session/' + session.getToken() + '/node/' + item.node_id + '/activate';
                    restService.postObject(uri, activateOptions, {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                            } else
                                handlers.error(data.hapi.hmessage);
                        },
                        error : function() {
                            handlers.error()
                        }
                    }, null);
                }

                this.analysis = function(item, complist, handlers) {
                    var uri = '/Session/' + session.getToken() + '/node/' + item.node_id + '/analysis';
                    restService.postObject(uri, complist, "", handlers, {});
                };
                this.getAllNodes = function(handlers) {
                    var uri = '/session/' + session.getToken() + '/node/index';
                    var object = null;
                    restService.getURI(uri, {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                            } else
                                handlers.error(data.hapi.hmessage);
                        },
                        error : function(error) {
                            handlers.error(error);
                        }
                    });
                };

                this.getNodeDataForGroup = function (handlers) {
                    var uri = '/session/' + session.getToken() + '/node/getNodeIndexForGroup';
                    var object = null;
                    restService.getURI(uri, {
                        success: function (data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                            } else
                                handlers.error(data.hapi.hmessage);
                        },
                        error: function (error) {
                            handlers.error(error);
                        }
                    });
                };
                this.getNodeData = function(item, handlers) {
                    var uri = '/session/' + session.getToken() + '/node/' + item.node_id + '/getdata';
                    restService.postObject(uri, null, {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                            } else
                                handlers.error(data, item);
                        },
                        error : function() {
                            handlers.error(item);
                        }
                    }, null);
                };

                function getBaselinesSuccess(data, handlers) {
                    baselines = [];
                    var i = 0, baselineid;
                    var paths = [];
                    for ( i = 0; i < data.length; i++) {
                      if (data[i].hasOwnProperty("baseline_id")) {
                        var str = data[i].baseline_url;
                        //No need to replace slashes here as engine is already converted to native separators
                    	//str = str.replace(new RegExp(/\\/g),"/");
							
                    	var baseline_version  = "";
						if (data[i].baseline_version !== "N/A")
							var baseline_version  = ' ' + data[i].baseline_version;		
							
                        var obj = {
                            id : data[i].locationid + '/' + data[i].baseline_id,
                            name : data[i].baseline_name + baseline_version + ' at ' + str,
                            uri : data[i].baseline_uri,
                            url: data[i].baseline_url,
                            size: data[i].baseline_size,
                            version: data[i].baseline_version,
                            baseline_name: data[i].baseline_name + baseline_version,
							baseline_state : data[i].baseline_state,
							baseline_status : data[i].baseline_status
                        };
                       baselines.push(obj);
                      }
                    }
                    if (handlers)
                        handlers.success(baselines);
                }

                function getBaselinesError(msg, handlers) {
                    if (handlers)
                        handlers.error(msg);
                }


                this.abortNode = function(node_id, handlers) {
                    var uri = '/session/' + session.getToken() + '/node/' + node_id + '/abort';
                    restService.postObject(uri, null, {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                            } else
                                handlers.error(data.hapi.hmessage);
                        },
                        error : function() {
                            handlers.error()
                        }
                    }, null);
                };

                this.abortAction = function(clearScheduleDateTime, handlers) {
                     var uri = '/session/' + session.getToken() + '/node/' + selectedItem.hapi.node_id + '/abort';
                     restService.postObject(uri, clearScheduleDateTime, {
                         success : function(data) {
                             if (data.hapi.hcode == 0) {
                                 handlers.success(data);
                             } else{
                                 handlers.error(data.hapi.hmessage);
							   }
                         },
                         error : function() {
                             handlers.error();
                         }
                     }, null);
                };

                //Activate REST API provides reboot now functionality for node
                this.rebootNode = function(node_id, handlers) {
                    var uri = '/session/' + session.getToken() + '/node/' + node_id + '/activate';
                    restService.postObject(uri, null, {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                            } else
                                handlers.error(data.hapi.hmessage);
                        },
                        error : function() {
                            handlers.error()
                        }
                    }, null);
                };
                this.deleteItem = function(handlers) {
                    var uri = '/session/' + session.getToken() + '/node/' + selectedItem.hapi.node_id + '/remove';
                    restService.postObject(uri, null, {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                                resource.removeSelectedUri('/Session/' + session.getToken() + '/Node/' + selectedItem.hapi.node_id + '/getdata');
                                // add a task
                                task.sourceName = selectedItem.hapi.name;

                                var notif = {
                                    summary : localizer.getString('hpsum.node.deletedNode'),
                                    status : 'ok',
                                    sourceName : task.sourceName,
                                };
                                notifications.add(notif, true);
                                resource.getIndexResults();
                            } else
                                handlers.error(data.hapi.hmessage);
                        },
                        error : function() {
                            handlers.error()
                        }
                    }, null);
                };

                this.getBaselineDetailsforId = function (baselineId) {
                    var len = installsets.length;
                    if(len>0)
                    {
                        var installset_baselines = baselines;
                        installset_baselines = installset_baselines.concat( installsets);
                        var i;
                         
                        if (baselineId == '')
                            return null;
                        for (i = 0; i < installset_baselines.length; i++) {
                            if (installset_baselines[i].id.match(baselineId))
                                return installset_baselines[i];
                        }
                        return null;
                    }
                    var i;
                    if (baselineId == '')
                        return null;
                    for ( i = 0; i < baselines.length; i++) {
                        if (baselines[i].id.match(baselineId))
                            return baselines[i];
                    }
                    return null;
                };

             this.getBaselineDetailsforName = function(baselineName)
            {
                var i;
                if(baselineName == '')
                    return null;
                for (i=0; i<baselines.length;i++){
                    if(baselines[i].name.match(baselineName))
                    return baselines[i];
                }
            };
                this.getAllBaselines = function(handlers) {
                	baselinePresenter.getBaselines({
                        success : function(data) {
                            getBaselinesSuccess(data, handlers)
                        },
                        error : function(msg) {
                            getBaselinesError(msg, handlers);
                        }
                    });
                };
				
				this.getGUAllBaselines = function(handlers) {
                	baselinePresenter.getGUBaselines({
                        success : function(data) {
                            getBaselinesSuccess(data, handlers)
                        },
                        error : function(msg) {
                            getBaselinesError(msg, handlers);
                        }
                    });
				};
                                          

                this.GetPendingTaskList=function(handlers)
                {
                   

                    for (var idx = 0; idx < iloTasklistlength; idx++) {

                        var updlist = "";
                        var activateby = "";
                        for (var updby = 0; updby < data.hapi.ilotasks.ilotask[idx].updatedby.length; updby++) {
                            if (updby != 0 && updby != data.hapi.ilotasks.ilotask[idx].updatedby.length)
                                updlist = updlist + ",";
                            updlist = updlist + data.hapi.ilotasks.ilotask[idx].updatedby[updby];
                        }

                        if (updlist.indexOf("Uefi") !== -1)
                            activateby = "After reboot";
                        else
                            activateby = "Immediately";


                        var item = {

                            id: data.hapi.ilotasks.ilotask[idx].id,
                            name: data.hapi.ilotasks.ilotask[idx].name,
                            state: data.hapi.ilotasks.ilotask[idx].state,
                            compname: data.hapi.ilotasks.ilotask[idx].component_name,
                            type: data.hapi.ilotasks.ilotask[idx].type,
                            version: data.hapi.ilotasks.ilotask[idx].version,
                            activate: activateby,

                            updatedby: updlist// data.hapi.ilotasks.ilotask[idx].updatedby//[updby]
                        };
                        iloTasklistArr.push(item);
                        


                    }
                }
				this.getGUInstallsets = function (item,handlers) {
				    var uri = '/session/' + session.getToken() + '/node/' + item.node_id + '/iloinstallset/index';///+ node_idN1localhost
				   
				  
				   
				    
				    var thishandlers = {
				        success: function (data) {
				            //var data = searchResults;
				            var numInstallset;
				             installsets = [];
				            
				            numInstallset = data.hapi.installsets.installset.length;
				            for (var idx = 0; idx < numInstallset; idx++) {
				                var item = {

				                    id: data.hapi.installsets.installset[idx].id,
				                    //name: data.hapi.installsets.installset[idx].name,
				                    name: data.hapi.installsets.installset[idx].name + ' ' + localizer.getString('hpsum.common.atiLORepository') + ' ' + data.hapi.installsets.installset[idx].date,
				                    uri: data.hapi.installsets.installset[idx].description,
				                    url: data.hapi.installsets.installset[idx].description,
				                    installset: true,
				                    isrecoveryset: data.hapi.installsets.installset[idx].isRecoverySet
				                };
				                installsets.push(item);
				            }
				             
				            handlers.success(installsets);
				        },
				        error: function (errorInfo) {
				            handlers.error(errorInfo);
				            //getInstallsetError(msg, handlers);
				        }
				    };
				    restService.getURI(uri, thishandlers);
				}

                this.getAllNodes = function(handlers) {
                    var uri = '/session/' + session.getToken() + '/node/index';
                    var thishandlers = {
                        success : function(data) {
                            handlers.success(data);
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    };
                    restService.getURI(uri, thishandlers);
                }
                this.getDedicatedNode = function (item,handlers) {
                    var uri = '/session/' + session.getToken() + '/node/' + item.node_id + '/index';
                    var thishandlers = {
                        success : function(data) {
                            handlers.success(data);
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    };
                    restService.getURI(uri, thishandlers);
                }

                this.haveItems = function() {
                    return resource.haveSome();
                };

                this.selectionLabel = function() {
                    return selectedItem.hapi.name;
                };

                this.getAllNodeTypes = function() {
                    return types;
                };
                this.getNodeStatus = function(item, handlers) {
                    var uri = '/session/' + session.getToken() + '/node/' + item.node_id + '/getstatus';
                    var thishandlers = {
                        success : function(data) {
                            handlers.success(data);
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    };
                    restService.getURI(uri, thishandlers);
                }
            this.getNodeStatusmulti = function (node_id,handlers) {
                 var uri = '/session/'+session.getToken() + '/node/' + node_id + '/getstatus';
                    var thishandlers =  {
                                success : function(data) {
                                    handlers.success(data);
                                },
                                error : function(errorInfo) {
                                    handlers.error(errorInfo);
                                }
                            };
                    restService.getURI(uri, thishandlers);              
            }
			
			this.postLiveLogData = function(nodeid, object, handlers) {
                    var uri = '/session/' + session.getToken() + '/node/' + nodeid + '/livelog';					
                    restService.postObject(uri, object, {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                            }
                            else
                                handlers.error(data.hapi.hmessage);
                        },
                        error: function (){
                            handlers.error()
                        }
                    }, null);
            };
            this.startInventory = function(item, handlers) {
                    var uri = '/session/' + session.getToken() + '/node/' + item.node_id + '/inventory';
                    var operationMode = item.hasOwnProperty('operation_mode') ? item.operation_mode : 0;
                    var scheduledDateTime = item.hasOwnProperty('set_schedule_date_time') ? item.set_schedule_date_time : "";
                    var iloManagementObj = null;
                    
                    var object = {
                        hapi : {
                            operation_mode : operationMode,
                            schedule_date_time : scheduledDateTime,
                            baselines : {
                                remove_existing_baselines:'true',
                                baseline : item.baselines
                            },
                            skip_prereqs: item.skip_prereqs,
                            ilo_management_options: iloManagementObj
                            
                        }
                    };
                    if (operationMode == 2) {
                        var installsetName = item.hasOwnProperty('install_set_name') ? item.install_set_name : "";
                        var installSetDescription = item.hasOwnProperty('install_set_description') ? item.install_set_description : "";
                        var cleanuponexit = item.hasOwnProperty('cleanup_onexit') ? item.cleanup_onexit : false;
                        var cleanupallonexit = item.hasOwnProperty('cleanupall_onexit') ? item.cleanupall_onexit : false;
                        iloManagementObj = {
                            install_set_name: installsetName,
                            install_set_description: installSetDescription
                        }

                        object.hapi.cleanupall_onexit = cleanupallonexit;
                        object.hapi.cleanup_onexit = cleanuponexit;
                        object.hapi.ilo_management_options = iloManagementObj;
                    }

                    restService.postObject(uri, object, {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                                resource.getIndexResults();
                            }
                            else
                                handlers.error(data.hapi.hmessage);
                        },
                        error: function (){
                            handlers.error()
                        }
                    }, null);
            };
			
	

			this.FindNodes = function(object,handlers)
			{
			var uri = '/session/'+session.getToken() + '/Complex/' + 'DiscoverNodes';
			
			restService.postObject(uri, object, {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                                resource.getIndexResults();
                            }
                            else
                                handlers.error(data.hapi.hmessage);
                        },
                        error: function (){
                            handlers.error()
                        }
                    }, null);
					
			};
			
			this.ScheduleNodes = function(node_id,action,scheduled,schedule_information,handlers)
			{
				var uri = '/session/'+ session.getToken() + '/node/' + node_id + '/schedule' ;
				var object={
						hapi: {
							  action : action,
							  scheduled : scheduled,
							  schedule_information: schedule_information,
							  node_id : node_id
						}
				};
				restService.postObject(uri,object, {
							success : function(data) {
								if (data.hapi.hcode == 0) {
									handlers.success(data);
									resource.getIndexResults();
								}
								else
									handlers.error(data.hapi.hmessage);
							},
							error: function (){
								handlers.error()
							}
						}, null);
			};
            this.startInventorymulti = function (node_id,baseline_id,handlers){
                 var uri = '/session/'+session.getToken() + '/node/' + node_id + '/inventory';
                 var object ={
                        hapi: {
                            baselines: {
                                baseline: baseline_id.id,
                            }
                        }
                };
                    restService.postObject( uri, object, {
                        success: function(data){
                            if(data.hapi.hcode == 0){
                                handlers.success(data);
                                resource.getIndexResults();
                            }
                            else
                                handlers.error(data.hapi.hmessage);
                        },
                        error : function() {
                            handlers.error()
                        }
                    }, null);
                };

                this.addItem = function(item, selectItem, handlers) {
                    // add a task
                    task.sourceName = item.name;
                    task.sourceUri = item.uri;
                    task.date = item.date;

                    item.status = 'unknown';
                    resource.addNode(item, {
                        success : function(data) {
        			        if(data.hapi.hcode != 5359){
                                onAddSuccess(data);
                            }
                            else
                                selectItem = false;

                            if (selectItem) {
                                resource.setSelectedUris([item.uri]);
                            }
                            resource.getIndexResults();
                            dispatcher.fire('itemChange', item);
                            handlers.success(data);
                        },
                        error : function (data){
							onAddError();
							handlers.error(data);
							}
                    });
                    trackUri = item.uri;
                    resource.getIndexResults();
                };
				        
                this.addItems = function(item, selectItem,handlers) {
                 
				 var message;
				 
                resource.addNodes( item,{
                  success: function(data){
                            onAddSuccess(data,message);
                            if (selectItem) {
                                resource.setSelectedUris([item.hapi.nodes.node[0].uri]);
                            }
                            handlers.success(data);
                        },
                  error:function(data){
                            handlers.error(data);
                        }
                  }, null);
                };

                this.refreshIndexResults = function() {
                    resource.getIndexResults();
                };

                this.setFilter = function(value) {
                    var filter = resource.getIndexFilter();
                    if (filter) {
                        if (filter.getUserQuery == value)
                            return;
                    }
                    var newFilter = new IndexFilter();
                    newFilter.data.userQuery = value;
                    resource.setIndexFilter(newFilter);
                    resource.getIndexResults();
                };

                /**
                 * @public
                 */
                this.init = function() {
                    resource.setCompareResourcesFunction(indexResultsCompare);
                    //This event is getting added multiple times, hence multiple getdata() calls
                    //Do this only once when first time NodePresenter initializes
                    if(!initDone)
                    	resource.on("selectionChange", selectionChange);
                    	
                    initDone = true;
                    this.getAllBaselines();
                };

                this.resource = function() {
                    return resource;
                }

                this.getSelection = function() {
                    return resource.getSelection();
                };

                this.getFWBaseline = function(baselines) {
                    var i;
                    if (baselines == undefined)
                        return null;
                    if (baselines.length == 0)
                        return null;
                    for (var i = 0; i < baselines.length; i++) {
                        var baseline = this.getBaselineDetailsforId(baselines[i]);
                        if (baseline) {
                            if (!baseline.name.match(/^Additional Package/i)) {
                                return baseline;
                            } else
                                return null;
                        }
                        return null;

                    }

                };
				//get both baseline and additional package.
				this.getFWBaselineAndPackage = function(baselines) {
                   
					var fwbaseline = null, addpackage = null;
					if(baselines != undefined && baselines.length > 0){
						for (var iter = 0; iter < baselines.length; iter++) 
						{
							var baseline = this.getBaselineDetailsforId(baselines[iter]);
							if (baseline) 
							{
								if (!baseline.name.match(/^Additional Package/i)) {
									fwbaseline = baseline;
								}
								else
								{
									addpackage = baseline;
								}
							}
						}
					}
					return {
							fwbaseline : fwbaseline,
							addpackage : addpackage
							};
                };

                this.allBaselines = function() {
                    return allBaselines;
                }
                this.getResetLink = function() {
                    var result = null;
                    if (session.canPerformAction('NODE', 'ADD')) {
                        var resource = router.location().split('/');
                        resource = resource[1];
                        result = linkTargetBuilder.makeLink(localizer.getString('hpsum.node.refresh'), null, 'show', resource, 'SHOW');
                    }
                    return result;
                };

                this.getAddLink = function(value) {
                    var result = null;
                    if (session.canPerformAction('NODE', 'ADD')) {
                    	var resource = router.location().split('/');
                		resource = resource[1];
						var nodeType = 'hpsum.node.' + value;//Human Factor changes req:HF02 dated 07/25/2014
						
                        result = linkTargetBuilder.makeLink(localizer.getString(nodeType), null, 'add', resource, 'ADD');
                    }
                    return result;
                };
                this.getCompConfDetail = function(item, handlers) {
                    var uri = "Session/" + session.getToken() + "/node/" + item.node_id + "/getcomponentconfigdata";
                    var thishandlers = {
                        success : function(data) {
                            handlers.success(data);
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    };
                    //Build the request and include all baselines as part of it
                    var request = {
                        hapi : {
                            baselines : {
                                baseline : [item.all_baselines]
                            },
                            component_id : item.component_name
                        }
                    };
                    restService.postObject(uri, request, "", thishandlers, {});
                };

                this.saveComponentConfig = function(item, compdata, handlers) {
                    var uri = "Session/" + session.getToken() + "/node/" + item.node_id + "/savecomponentconfigdata";
                    var thishandlers = {
                        success : function(data) {
                            handlers.success(data);
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    };
                    restService.postObject(uri, compdata, "", thishandlers, {});
                };

            this.createReport = function(request, handlers) {
                    var uri = "Session/" + session.getToken() + "/report/create";
                    var thishandlers = {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                            } else {
                                handlers.error(data.hapi.hmessage);
                            }
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    };
                    restService.postObject(uri, request, "", thishandlers, {});

            };
			
			this.setSessionAttribute = function(request, handlers) {
                    var uri = '/Session/' + session.getToken() + '/setattributes';
                    var thishandlers = {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                            } else {
                                handlers.error(data.hapi.hmessage);
                            }
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    };
                    restService.postObject(uri, request, "", thishandlers, {});
					
            };
            
            this.generateReport = function(reportId, handlers) {
                    var uri = "Session/" + session.getToken() + "/report/" + reportId + "/generate";
                    var thishandlers = {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                            } else {
                                handlers.error(data.hapi.hmessage);
                            }
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    };

                    restService.postObject(uri, null, "", thishandlers, {});
            };
            
            this.getReportStatus = function(reportId, handlers) {
                    var uri = '/session/' + session.getToken() + '/report/' + reportId + '/getstatus';
                    var thishandlers = {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                handlers.success(data);
                            } else {
                                handlers.error(data.hapi.hmessage);
                            }
                        },
                        error : function(errorInfo) {
                            handlers.error(errorInfo);
                        }
                    };
                    restService.getURI(uri, thishandlers);
            };

			this.getAllReports = function(handlers) {
            	var uri = '/session/'+session.getToken() + '/report/index';
				restService.getURI( uri, {
					success: function(data){
						if(data.hapi.hcode == 0){
							handlers.success(data);
						}
						else {
							handlers.error(data.hapi.hmessage);
						}
					},
					error: function (error){
						handlers.error(error);
					}
				});
            };

			this.deleteReport = function(item, handlers) {
					var uri = '/session/' + session.getToken() + '/report/' + item.report_id + '/remove';
					var object = {
						hapi : {
							report_id : item.report_id
						}
					};
					restService.postObject(uri, object, {
						success : function(data) {
							if (data.hapi.hcode == 0) {
								handlers.success(data);
							} else {
								handlers.error(data.hapi.hmessage);
							}
						},
						error : function(data) {
							handlers.error(data);
						}
					}, null);
			};
				
            this.restore = function(nodeId) {
                var uri = '/Session/' + session.getToken() + '/node/' + nodeId + '/restore';
                restService.postObject(uri, null, {
                    success : function(data) {
                            resource.getIndexResults();
                    },
                    error : function() {
                    }
                }, null);
            };

            this.getUpdateList = function(param,handlers){				
				var nodeId;
				var uri;
				if(param.match(/isDeployResults/i))
				{		var params = param.split('/');
                		nodeId = params[0];
						uri = '/Session/' + session.getToken() + '/node/' + nodeId + '/getupdatelist?isDeployResults=Yes';
				}
				else
				{
					nodeId=param;
					uri = '/Session/' + session.getToken() + '/node/' + nodeId + '/getupdatelist';
				}
                restService.getURI(uri , handlers);

            };

            this.getComponentLogs = function(nodeId , componentlist , handlers )
            {
                var uri = '/Session/' + session.getToken() + '/node/' + nodeId + '/getcomponentlogs';
                restService.postObject(uri, 
                                   {
                                      hapi: { 
                                                components: { component: componentlist } 
                                            }
                                   },"" , 
                                   handlers , {} );
            };
            
			this.setNodeForAdvOptions = function(node) {
				nodesAdvOptions.push(node);
			}
			this.getNodesForAdvOptions = function() {
				return nodesAdvOptions;
			}
			
			/*
			 * getUINodeType 
			 * Accept node type as per hpsum engine and returns equivalent UI location for the node type.
			 */
			this.getUINodeType = function(node_type) {
				var uinodetype = "unknown";
				
				switch(node_type)
				{
					case 'unknown':
					case 'host':
						uinodetype = "unknown";
						break;
					case 'windows':
					case 'linux':
					case 'hpux':
						uinodetype = "server";
						break;
					case 'vmware':
						uinodetype = "vmware";
						break;
					case 'ilo':
					case 'ilo2':
					case 'ilo3':
					case 'ilo4':
					case 'ilo5':
				  case 'ilo6':
				  case 'ilo7':
					case 'integrityilo2':
					case 'integrityilo3':
						uinodetype = "ilo";
						break;
					case 'ipdu':
						uinodetype = "ipdu";
						break;
					case 'switch':
					case 'fc_switch':
					case 'switch_cisco':
					case 'switch_brocade':
					case 'switch_qlogic':
					case 'sas_switch':
						uinodetype = "switch";
						break;
					case 'oa':
					case 'sdx':
					case 'sd2':
						uinodetype = "enclosure";
						break;
					case 'virtual_connect':
						uinodetype = "vc";
						break;
					case 'moonshot':
						uinodetype = "moonshot";
						break;
					case 'ilo_federation':
						uinodetype = "ilofederation";
						break;
					default:
						uinodetype = "unknown";
						break;
				}
				
				return uinodetype;
			}
			
			/*
			 * getGeneralEditHref 
			 * Accept current router location and UI node type as input and 
			 * returns context based Href for General | Edit hyperlink
			*/
			this.getGeneralEditHref = function(router_location, uitype) {
				if(router_location.indexOf("/node") == 0) {
				   return ("#/node/edit/general");
				}
				else
				{
				 return ("#/" + uitype + "/edit/general");
				}
			};
			
            /**
             * Add a listener for a specified event.
             * @public
             * @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.length === 0)
							{
								var currentLocation = router.location();
								if (currentLocation.match(/guided-update/i) ) {
									var nodeId = "N1localhost";
								uris[0] = '/session/' + session.getToken() + '/node/' + nodeId + '/getdata';
								}
							}
                      
                            if ((uris[0] == undefined) && selectedItem) {
                            	uris[0] = '/Session/' + selectedItem.hapi.node_session + '/Node/' + selectedItem.hapi.node_id + '/getdata';                            	
                            }
                            if (uris && uris.length === 1) {
                                //var url = resource.getSelection().uris[0].replace(/enclosure|fc_switch|windows|linux|vmware|switch|host/, 'node');
                                resource.getItem(uris[0], {
                                    success : callback
                                }, true);
                                // resource.getItem(uris[0], {success: callback});
                            }
                            break;
                        case 'itemError':
                            uris = resource.getSelection().uris;
                            if (uris && uris.length === 1) {
                                //var url = resource.getSelection().uris[0].replace(/enclosure|fc_switch|windows|linux|vmware|switch|host/, 'node');
                                resource.getItem(uris[0], {
                                    error : callback
                                });
                                // resource.getItem(uris[0], {success: callback});
                            }
                            break;
                    }
                };

                this.off = function(eventName, callback) {
                    dispatcher.off(eventName, callback);
                };
                
                this.initialized = function() {
                	return initDone;
                };
				
				this.selectItem=function(uri)
				{
					resource.clearSelectedUris();
					var uriArray=new Array();
				    uriArray[0]=uri;
					resource.setSelectedUris(uriArray);
				};
            }

            return new NodePresenter();
        }());

    return NodePresenter;
    });
