// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/* This is a Resource object for Nodes resource.
 * The resource object created for particular type of resource and association with other resources.
 */
define(['hp/model/Resource',
'hp/services/IndexService',
'hp/core/EventDispatcher',
'hp/services/REST',
'hp/model/Session'
],
function(Resource,indexService,eventDispatcher,restService,session) {"use strict";
	
	var NodeResource = (function(){
		
		function NodeResource() {
			var prefix = '/hpsum';
			var nodeResource;
			//Derive from Resource
			var category= ['windows','linux','hpux','vmware','enclosure','switch','fc_switch','host','rack','unknown'];
			 Resource.call(this, category);
			 var index;
			function hoursAgo(hours) {
                var now = new Date();
                return new Date(now.getTime() - (1000 * 60 * 60 * hours));
            }
			 
			 nodeResource =this;
			 this.category='nodes';
			 // Inits nodes for mockup

			function OnAddNodeSuccess(data,item){
				
				var notDetails={
			 		summary:null,
			 		details:null
			 	};
				var alertTemplate = {
                        category: 'alert',
                        sourceUri: item.uri,
                        sourceName: item.name,
                        notes: []
                    };
                    
				var alert = $.extend({name: 'Added '+item.name,
                uri: '/alert/alert-t1',
                status: 'info', owner: session.getUser(), state: 'active',
                date: hoursAgo(36).toISOString()}, alertTemplate);
                //indexService.addItem('alert', alert);
                item.index = data.hapi.node_id;
                if(item.username && item.password)
                    item.state = 'discovery';
                else {	
                	item.state = 'init';
                	notDetails.summary='Need Credentials';
			 		notDetails.details= '<p><a href="#/node/edit/credentials"> Need Credentials</a>.</p>';
                }  
                item.stateDetails=notDetails,
                item.uri = '/Session/'+session.getToken() + '/Node/' + data.hapi.node_id + '/getdata';

				
			}

            function OnNodesAddSuccess(data,item, ReturnPresenterHandlers){
                
                var notDetails={
                    summary:null,
                    details:null
                };
                var alertTemplate = {
                        category: 'alert',
                        sourceUri: item.hapi.nodes.node[0].uri,
                        sourceName: item.hapi.nodes.node[0].name,
                        notes: []
                    };
					
				//call getstatus to find the nodes added properly.
				var complex_id = ""; 
				if(data != undefined){
					complex_id = data.hapi.complex_id;
				}
				var node_uri = "/Session/" + session.getToken() + "/complex/" + complex_id ;
				var timer = setInterval(function() {
					restService.getURI(node_uri + "/getstatus", {
						success : function(nodeDetailsData) {
							if(nodeDetailsData.hapi.command_status === 0){
								if(nodeDetailsData.hapi.hasOwnProperty("nodes") && nodeDetailsData.hapi.nodes.hasOwnProperty("node") && nodeDetailsData.hapi.nodes.node.length >0){
									clearInterval(timer);
									for(var nodeDataCount =0; nodeDataCount < nodeDetailsData.hapi.nodes.node.length; nodeDataCount++)
									{										
										for(var itemDataCount=0; itemDataCount < item.hapi.nodes.node.length; itemDataCount++)
										{
											if(item.hapi.nodes.node[itemDataCount].ip == nodeDetailsData.hapi.nodes.node[nodeDataCount].ip && nodeDetailsData.hapi.nodes.node[nodeDataCount].exists){
												item.hapi.nodes.node.splice(itemDataCount, 1);
												break;
											}
										}
									}
									if(item.hapi.hasOwnProperty("nodes") &&  item.hapi.nodes.hasOwnProperty("node") && item.hapi.nodes.node.length > 0){
										var id = generateId(item.hapi.nodes.node[0].ip);

										var alert = $.extend({name: 'Added '+ item.hapi.nodes.node[0].name,
										uri: '/alert/alert-t1',
										status: 'info', owner: session.getUser(), state: 'active',
										date: hoursAgo(36).toISOString()}, alertTemplate);
										//indexService.addItem('alert', alert);
										item.hapi.nodes.node[0].index = id;
										if(item.hapi.nodes.node[0].username && item.hapi.nodes.node[0].password)
										    item.hapi.nodes.node[0].state = 'discovery';
										else {  
											item.hapi.nodes.node[0].state = 'init';
											notDetails.summary='Need Credentials';
											notDetails.details= '<p><a href="#/node/edit/credentials"> Need Credentials</a>.</p>';
										}  
										item.hapi.nodes.node[0].stateDetails=notDetails;
										item.hapi.nodes.node[0].uri = '/Session/'+session.getToken() + '/Node/' + id + '/getdata';
										ReturnPresenterHandlers.success(nodeDetailsData);				
									}
									else
									{	
										clearInterval(timer);
										ReturnPresenterHandlers.error(nodeDetailsData);
									}
								}
							}
							else
							{
								if(nodeDetailsData.hapi.command_status > 1)
								{
									clearInterval(timer);
									ReturnPresenterHandlers.error(nodeDetailsData);
								}
							}
						},
						error : function(errorInfo) {								
							clearInterval(timer);
							ReturnPresenterHandlers.error(nodeDetailsData);
						}
					});						
				}, 10000);
            }

            function generateId(ipaddress)
            {
                var id;
                id = "N1" + ipaddress.replace(/\./g,"h");
                id = id.replace(/:/g,"h");
                return id;
            }
			
			function OnAddNodeFailed(data,item){
				
				var alertTemplate = {
                        category: 'alert',
                        sourceUri: item.uri,
                        sourceName: item.name,
                        notes: []
                    };
                    
				
				var alert = $.extend({name: 'Add Failed '+item.name,
                uri: '/alert/alert-t1',
                status: 'info', owner: session.getUser(), state: 'active',
                date: hoursAgo(36).toISOString()}, alertTemplate);
                //indexService.addItem('alert', alert);
			}
			 
			 this.addNode = function(item, handlers){

			 	/*
			 	if(!baseline || !username || !password) {
			 		if(!baseline && !username && !password){
			 			notDetails.summary='Need Credentials and Baseline';
			 			notDetails.details= '<p><a href="#/node/edit/baseline"> Need Credentials and Baseline</a>.</p>';
			 		}
			 		else if(!baseline){
			 			notDetails.summary='Need Baseline';
			 			notDetails.details= '<p><a href="#/node/edit/baseline"> Need Baseline</a>.</p>';			 			
			 		}else {
			 			notDetails.summary='Need Credentials';
			 			notDetails.details= '<p><a href="#/node/edit/credentials"> Need Credentials</a>.</p>';
			 		}
			 		
			 		
			 	}*/
			 	/*var item = indexService.addItem(type, {
                        category: type,
                        name: name,
                        uri: '/' + type + '/item' + index,
                        status: status,
                        nodeType:nodeType,
                        baseline: baseline,
                        changing: ((index % 3) === 0),
                        updatedAt: (new Date()).toISOString(),
                        state: 'init',
                        stateDetails: notDetails,
                        index: this.index,
                        attributes: {}
                    });
                var baselineuri = '/baseline/item' + item.baseline;
               indexService.getIndexForResource(baselineuri, {
                	success: function(baselineobj){
                		if(baselineobj)
                			indexService.addAssociation('BASELINE_TO_NODE', baselineobj, item);
                	},
                	error: function (){
                		
                	}
                	
                });*/
                
                    
					var alertTemplate = {
                        category: 'alert',
                        sourceUri: item.uri,
                        sourceName: item.name,
                        notes: []
                    };
                    
                    var object ={
                    	hapi: {
                    		ip: item.name,
							name: item.name,
                    		type: item.category,
                            description:item.description,
                            group: item.group,
                            ilo_federation: item.ilo_federation,
                            moonshot_switch_credentials: item.moonshot_switch_credentials,
                    		node_skip: item.node_skip,
							skip_prereqs: item.skip_prereqs,
                    		baselines: {
                    		baseline: item.baseline,
                    		},
							use_current_credentials : item.use_current_credentials,
							use_vcenter: item.use_vcenter,
							vcenter_ip: item.vcenter_ip,
							vcenter_username: item.vcenter_username,
							vcenter_password: item.vcenter_password,
							use_sudo: item.use_sudo,
                    		su_username: item.su_username,
                    		su_password: item.su_password,
                    		associated_node : item.associated_node,
							auto_add_assoc_nodes: item.auto_add_assoc_nodes,
							use_sshkeyfile: item.use_sshkeyfile,
                    		username: item.username,
                    		password: item.password,
							ilo_username: item.ilo_username,
							ilo_password: item.ilo_password,
							skip_apptoken: item.skip_apptoken
            			}
            		};
					
					if(item.use_sshkeyfile == true) {
						object.hapi.sshkeyfile_username = item.sshkeyfile_username;
						object.hapi.sshkeyfile_location = item.sshkeyfile_location;
						object.hapi.sshkeyfile_passphrase = item.sshkeyfile_passphrase;
					}
					
                    var options = {
                    	encodeResults: false,
                    	encodeErrors: false
                    };
                    var sessionurl = '/session/'+session.getToken();
					restService.postObject( sessionurl + '/node/add', object,{
						success: function(data){
							if(data.hapi.hcode == 0){
								OnAddNodeSuccess(data,item);
								handlers.success(data);
							}
							else 
								handlers.error(data.hapi.hmessage);
                   	},
                   		error: function () {
                   			var alert = $.extend({name: 'Add Failed '+item.name,
                        	uri: '/alert/alert-t1',
                        	status: 'failed', owner: 'HPSUM', state: 'active',
                        	date: hoursAgo(36).toISOString()}, alertTemplate);
                   			indexService.addItem('alert', alert);
                   		}
                 }, options);
			 };

             this.addNodes = function(item, handlers){
                var uri = '/Session/' + session.getToken() + '/complex/add'; 
                var itemame;
                if(item.hapi.nodes.node.hasOwnProperty("length"))
                   {
                       var len = item.hapi.nodes.node.length;
                       if(len > 1)
                       {
                            itemame = item.hapi.nodes.node[0].ip + " - " + item.hapi.nodes.node[len-1].ip;

                       } else{ 
                            
                            itemame = item.hapi.nodes.node[0].ip ;
                       }
                   }
                restService.postObject(uri,item,{
                    success: function(data){
                              OnNodesAddSuccess(data,item, handlers);
                    },
                    error: function(){
                        var alert = $.extend({name: 'Add Failed '+ itemame,
                            uri: '/alert/alert-t1',
                            status: 'failed', owner: 'HPSUM', state: 'active',
                            date: hoursAgo(36).toISOString()}, alertTemplate);
                            indexService.addItem('alert', alert);
                    }

                })

             }
			 
			 this.init =function(count){
			 	 var i, status, name, item,description, nodeType,prefix='Node';
			 	index =1001;
                indexService.addCategory('unknown');
                indexService.addCategory('windows');
                indexService.addCategory('linux');
                indexService.addCategory('hpux');
                indexService.addCategory('switch');
                indexService.addCategory('enclosure');
                indexService.addCategory('fc_switch');
                indexService.addCategory('host');
                                
                for (i = 1; i <= count; i += 1) {
                    name = prefix + ' ' + i;
                    // make most 'ok'
                    if (i % 1 === 0) {
                        status = ['all', 'scanning', 'scan-complete', 'scheduled','web','error'][i % 6];
                    } else {
                      //name += ' make it much longer to see what happens'; /// !!!
                        status = 'ok';
                    }
                    description = name;
                    nodeType = 'Windows Server';
                   // this.addNode(name, description, status, nodeType,1);

                }
			 	
			 };
			
		}
		return new NodeResource();
	}());
    return NodeResource;
});
