/*******************************************************************************
 * Copyright (c) 2007, 2008 CA, Inc. and others
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CA Inc. - initial API and implementation
 *     IBM Corporation - Defects and enhancements
 *******************************************************************************/
dojo.provide("org.eclipse.cosmos.provisional.dr.ps.components.widget.RegisterPartialDialog");
dojo.require("org.eclipse.cosmos.provisional.dr.ps.components.utility.common");
dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.Textarea");

dojo.declare(
   "org.eclipse.cosmos.provisional.dr.ps.components.query.RegisterPartialDialog",
	// superclass	
   [org.eclipse.cosmos.provisional.dr.ps.components.utility.BasicQuery,
    org.eclipse.cosmos.provisional.dr.ps.components.utility.BasicUtility],
	{
		labelDialogQuery:"",
		registrationService:"json?service=org/eclipse/cosmos/internal/dr/drs/service/outputter/RegistrationOutputter",		
		brokerService:"json?service=org/eclipse/cosmos/internal/dr/drs/service/outputter/BrokerOutputter",		
		builder:null,
		_message: dojo.i18n.getLocalization("nls.org.eclipse.cosmos.provisional.dr.ps.components", "widget"),
		mode:true,				// Indicates the mode this dialog is in; i.e. registration(true) or deregistration(false)		
		
		bindInput: function(data, callbackMethod)
		{	
	   		// Show the progress dialog while we retrieve the query response
			var progressDialog = new org.eclipse.cosmos.provisional.dr.ps.components.utility.ProgressDialog({title: this._message.COMMON_WAIT});
			progressDialog.show();
	   
			progressDialog.setMessage(this._message.REGISTER_TASK_CMDBf);
			
	   		var _self = this;
	   		// Retrieve a list of federating CMDBs
	   		this.UIContext.submitQuery(
			{
					item:data,
					queryObject:new org.eclipse.cosmos.provisional.dr.ps.components.utility.BasicQuery({queryHandler:_self.brokerService+"&query=cmdbf&epr="+escape(this.epr)}), 
					onItem:function(federatingCMDBs)
					{
						progressDialog.setMessage(_self._message.REGISTER_TASK_QUERY);
			    		data.getResponse[0]({item:data,onItem:function(response)
			        	{   
			    			// Determine the configuration items included in the query response
			    			// populate the grid with CIs
			    			progressDialog.setMessage(_self._message.REGISTER_TASK_CIs);
			    			var postData = "cmd=query&queryResp=" + escape(response) + "&mdrepr="+escape(data.epr);
			    			_self.UIContext.submitQuery(
			    					
			    				// invoke the Registration outputter to query a list of CIs 
			    				{
			    					item:data,
			    					queryObject:new org.eclipse.cosmos.provisional.dr.ps.components.utility.BasicQuery({queryHandler:_self.registrationService, postData:postData}), 
			    					onItem:function(configurationItems)
			    					{			    					
				    					// Destroy the progress dialog, so the partial registration dialog
					        			// can be displayed
					        			progressDialog.destroy();
					        			
					        			_self.destroy();
					        			var dialogTitle = _self.mode ?  _self._message.REGISTER_DLG_TITLE : _self._message.DEREGISTER_TITLE;
					    	    		_self.builder = new org.eclipse.cosmos.provisional.dr.ps.components.widget.RegisterPartialDialog(
					    	    				{ callback: callbackMethod, 
					    	    				  registrationService: _self.registrationService, 
					    	    				  brokerService:_self.brokerService, 
					    	    				  data: data,
					    	    				  labelQuery:_self.labelDialogQuery, 
					    	    				  title:dialogTitle, 
					    	    				  epr:data.epr, 
					    	    				  queryResp:response, 
					    	    				  UIContext:_self.UIContext,
					    	    				  cmdbflist:federatingCMDBs,
					    	    				  _message:_self._message,
					    	    				  configItems:configurationItems,
					    	    				  selectAll:_self._message.COMMON_SELECT_ALL,
					    	    				  deselectAll:_self._message.COMMON_DESELECT_ALL
					    	    				});
					    	    		
					    	    		_self.builder.show();	

			    					}, 
			    					queryProp:"query"
			    				});			    						    			    		    	    		
			        	}});
					}, 
					queryProp:"query"
			});
		},
		
		render: function(input){
			this.builder.destroy();
			this.builder = null;
			return input;
		},
		
		destroy:function()
		{
			this.destroyWidgets(
					["registerPartialDialog", "registerGrid", 
			         "selectAllBtn", "deselectAllBtn", 
			         "cmdbfGrid", "regbutton", "cancelBtn"]);
		}
	}
); 

 dojo.declare(
	"org.eclipse.cosmos.provisional.dr.ps.components.widget.RegisterPartialDialog",
	[dijit._Widget, dijit._Templated, dijit._Container, org.eclipse.cosmos.provisional.dr.ps.components.utility.BasicUtility], 
	{
	 	rows:12,
	 	cols:80,
		labelQuery:"",
		dialogIcon:"",
		templatePath:dojo.moduleUrl("org.eclipse.cosmos.provisional.dr.ps.components.widget", "html/RegisterPartialDialog.html"),
		widgetsInTemplate: true,
		widgetId: "registerPartialDialog",
		gridWidget: null,
		cmdbfWidget: null,
		cmdbflist: null,
		mdrEPR: null,		
		cis: null,
		mode: "register",		
		_message: null,
		configItems: null,
		
		show: function()
		{
			this.dialogBox.show();
						
			// Populate the grid view for configuration items
            var regview = 
            {
				cells: [
				        [
				         {name: ' ', get: this.getCheckBox, width: "16px"}, 
				         {name: this._message.REGISTER_TYPE, field: 0, width: "34px"}, 
				         {name: this._message.REGISTER_LOCAL_ID, field: 1, width: "350px"}
				        ]
				       ]
            };
            this.gridWidget = dijit.byId("registerGrid");
            this.setupGridWidget(this.gridWidget, regview, this.configItems);
            
			// Populate the grid view for CMDBfs		
            var cmdbfview = {
                    cells: 
                    [
                    	[
                    	 	{name: ' ', field: -1, width: "16px"}, 
                    	 	{name: this._message.REGISTER_CMDBf, field: 0, width: "390px"}
                    	]
                    ]
            };      
            
            this.cmdbfWidget = dijit.byId("cmdbfGrid");			
			var response = this.cmdbflist;
			this.cmdbfWidget.onStyleRow = function (inRow)
			{
				with (inRow) {											
					
					var NODE_CLASS_INDEXT = 2;
					if (response[inRow.index][NODE_CLASS_INDEXT] == null)
					{
						return;
					}
					
					var cssClass = response[inRow.index][NODE_CLASS_INDEXT] + "InRegistrationIcon";							
					customClasses += ' ' + cssClass;
					
					if (selected)
					{
						customClasses += " registrationSelected";
					}							
				}
				
			};
			this.setupGridWidget(this.cmdbfWidget, cmdbfview, this.cmdbflist);		
			this.cmdbfWidget.selection.selected = [true];
			this.cmdbfWidget.selection.selectedIndex = 0;
			this.cmdbfWidget.render();
		},
		
		
		getCheckBox: function(rowIndex)
		{
			return '<input dojotype="dijit.form.CheckBox" name="ci' + rowIndex + '" id="ci' + rowIndex + '" type="checkbox" checked="checked">';
		},
		
		
		onSelectAll:function()
		{
			// Invoked when the select all button is clicked
			this.changeCheckState(true);
		},
		
		
		onDeselectAll:function()
		{
			// Invoked when the deselect all button is clicked
			this.changeCheckState(false);
		},
		
		
		changeCheckState:function(check)
		{			
			var counter = 0;
			var checkBox = dojo.byId("ci" + counter);
			
			while (checkBox != null)
			{
				if (checkBox.checked != check)
				{
					checkBox.checked = check;
				}
				counter++;
				checkBox = dojo.byId("ci" + counter);
			}
		},
		
		
		setupGridWidget: function(gridWidget, structure, response)
		{			
			gridWidget.selection.multiSelect = false;
			
			// define the grid layout containing the view
            var gridLayout = [structure];
			
			// create a model from the outputter JSON response
			var gridModel = new dojox.grid.data.Table(null, response);

			// set the grid model
			gridWidget.setModel(gridModel);

			// set the grid layout
			gridWidget.setStructure(gridLayout);
			
			// redraw the grid
			gridWidget.render();
		},
		
		
		destroy: function()
		{
			this.destroyWidgets(
					["registerGrid", "selectAllBtn", "deselectAllBtn", 
			         "cmdbfGrid", "regbutton", "cancelBtn"]);
			
			if (this.dialogBox)
			{
				this.dialogBox.onCancel();
			}

		},
		
		
		onRegister: function()
		{
			this.cis  = this.findCISelection();
			
			// Make sure exactly one federating CMDB is selected
			if (this.cmdbfWidget.selection.getSelectedCount() != 1)
			{
				dojo.publish("org.eclipse.cosmos.provisional.dr.ps.components.utility.ErrorHandler", [{message:this._message.REGISTER_ERROR_CMDBf, prompt:true, severity:4}]);				
				return;
			} 
			else if (this.cis == null || this.cis.length <= 0)
			{
				dojo.publish("org.eclipse.cosmos.provisional.dr.ps.components.utility.ErrorHandler", [{message:this._message.REGISTER_ERROR_CIs, prompt:true, severity:4}]);				
				return;
			}
			
			
			// Determine the EPR of the federating CMDB
			var cmdbfEPR = this.cmdbflist[this.cmdbfWidget.selection.selectedIndex][1];
						
			// Perform the registration
			var _self= this;
			var postData = 	"&cmd=" + this.mode + 
							"&queryResp=" + escape(this.queryResp) + 
							"&cmdbfEPR=" + cmdbfEPR + 
							"&mdrEPR=" + this.mdrEPR + 
							this.cis;
			
			this.destroy();
			
			// Show the progress dialog
			var progressDialog = new org.eclipse.cosmos.provisional.dr.ps.components.utility.ProgressDialog({title: this._message.COMMON_WAIT});
			progressDialog.setMessage(this._message.REGISTER_TASK_REQUEST);
			progressDialog.show();						
			
			this.UIContext.submitQuery(
					
				// invoke the Registration outputter to query a list of CIs 
				{
					item:this.data,
					queryObject:new org.eclipse.cosmos.provisional.dr.ps.components.utility.BasicQuery({queryHandler:this.registrationService, postData:postData}), 
					onItem:function(response)
					{			    					
						var dialogTitle = _self.mode == "deregister" ? 
								_self._message.DEREGISTER_RESPONSE_TITLE	:
								_self._message.REGISTER_RESPONSE_TITLE;
											
						var regResponse = new org.eclipse.cosmos.provisional.dr.ps.components.widget.RegisterResponseDialog(
								{	statusService:_self.statusService,
									brokerService:_self.brokerService, 
									title:dialogTitle,
									jsonData: response,
									rootLabel: dialogTitle,
									closeCaption: _self._message.COMMON_CLOSE});
						
						progressDialog.destroy();
						regResponse.show();		
					}, 
					queryProp:"query"
				});			    						    			    		    	    		
			
		},
		
		
		findCISelection: function()
		{
			// Summary: Determine the check boxes beside configuration items that
			// have been checked.			
			var checkBoxCounter = 0;
			var parameterIndexCounter = 0;
			var ciCheckBox = dojo.byId("ci" + checkBoxCounter);
			var selectedLocalIds = "";
			
			while (ciCheckBox != null)
			{
				if (ciCheckBox.checked && this.configItems[checkBoxCounter][1])
				{
					selectedLocalIds += "&localid" + parameterIndexCounter + "=" + this.configItems[checkBoxCounter][1];
					parameterIndexCounter++;
				}
				
				checkBoxCounter++
				ciCheckBox = dojo.byId("ci" + checkBoxCounter);
			}
			
			return selectedLocalIds;
		},
		
		
		onCancel: function(){
			this.destroy();
		},
		
		postMixInProperties: function(){
			// set the dialog in the dialog box dependent on whether it is register or deregister
			// this should go in a jprop file, but as yet its unknown where (Martin).
			if ( this.title.substr( 0, 5 ) == "Regis" )
			{
				this.dialogIcon = "<span class='dialogRegisterPartialWinIcon'></span>" ;
			}
			else
			{
				this.dialogIcon = "<span class='dialogDeRegisterWinIcon'></span>";
			}

			//call superclass
			org.eclipse.cosmos.provisional.dr.ps.components.widget.RegisterPartialDialog.superclass.postMixInProperties.apply(this, arguments);
		},
		
		postCreate: function(){
			//call superclass
			org.eclipse.cosmos.provisional.dr.ps.components.widget.RegisterPartialDialog.superclass.postCreate.apply(this, arguments);
			var idLength = this.id.length;
			var index =  this.id.substring(idLength-2, idLength);
			this.dialogBox = dijit.byId(this.widgetId);			
			this.mdrEPR = this.epr;
						            		
			if ( this.title.substr( 0, 5 ) == "Dereg" )
			{
				this.mode = "deregister";
				
				var regbutton = dijit.byId("regbutton");
				regbutton.setLabel( "Deregister" );
			}

			
			// Update the instructions
			var reglabel = document.getElementById("instruction1");
			reglabel.textContent = this._message.REGISTER_PARTIAL_INSTRUCTION_1 + this.mode + ":";	
			
			reglabel = document.getElementById("instruction2");
			reglabel.textContent = this._message.REGISTER_PARTIAL_INSTRUCTION_2_1;
			
			var fontElement = document.createElement("font");		
			fontElement.setAttribute("color", "red");				
			fontElement.setAttribute("style", "font-weight: bold");
			fontElement.textContent = this._message.REGISTER_PARTIAL_INSTRUCTION_2_2;			
			reglabel.appendChild(fontElement);
			
			var spanElement = document.createElement("span");		
			spanElement.textContent = this._message.REGISTER_PARTIAL_INSTRUCTION_2_3;
			reglabel.appendChild(spanElement);	
			
			dojo.connect(this.dialogBox.closeButtonNode,"onclick", this, "destroy");
		}
		
	}
);      
