/*******************************************************************************
 * 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 - Bug fix 220495
 *******************************************************************************/
dojo.provide("org.eclipse.cosmos.provisional.dr.ps.components.widget.RegisterDialog");
dojo.require("org.eclipse.cosmos.provisional.dr.ps.components.utility.common");
dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");
dojo.require("org.eclipse.cosmos.provisional.dr.ps.components.widget.RegisterResponseDialog");

dojo.declare(
	"org.eclipse.cosmos.provisional.dr.ps.components.query.RegisterDialog",
	
	// superclass	
	[org.eclipse.cosmos.provisional.dr.ps.components.utility.BasicQuery, 
    org.eclipse.cosmos.provisional.dr.ps.components.utility.BasicUtility],
    
	{
		labelDialogQuery:"",
		_message: dojo.i18n.getLocalization("nls.org.eclipse.cosmos.provisional.dr.ps.components", "widget"),
		statusService:"json?service=org/eclipse/cosmos/internal/dr/drs/service/outputter/StatusResponseOutputter",		
		brokerService:"json?service=org/eclipse/cosmos/internal/dr/drs/service/outputter/BrokerOutputter",		
		builder:null,
		mode:true,					// Indicates the mode this dialog is being used in;
									// true indicates registration and false indicates deregistration			
		
		bindInput: function(data, callbackMethod){
	   			   	
			var registerEPR = this.UIContext.getService(data, "http://cmdbf.org/schema/1-0-0/registration");
			if (registerEPR == null)
				return;  
			
			var dataManagerEPR = this.UIContext.getService(data, "http://www.eclipse.org/cosmos/datamanager");
			
			var queryEPR = this.UIContext.getService(data, "http://cmdbf.org/schema/1-0-0/query");
			
			// Show the progress dialog while we retrieve the MDRs from the broker
			var progressDialog = new org.eclipse.cosmos.provisional.dr.ps.components.utility.ProgressDialog({title: this._message.COMMON_WAIT});
			progressDialog.show();
			
			var _self = this;
			
			// Perform the query
			this.UIContext.submitQuery(
					
					// invoke the Broker outputter to return a list of MDRs to the onItem callback function
					{item:data,queryObject:new org.eclipse.cosmos.provisional.dr.ps.components.utility.BasicQuery({queryHandler:this.brokerService+"&query=mdr&epr="+escape(this.epr)+"&exclude="+escape(dataManagerEPR)}), 
					onItem:function(queryResponse){
											
						progressDialog.destroy();
						_self.destroy();
						var dialogTitle = _self.mode ? _self._message.REGISTER_DLG_TITLE : _self._message.DEREGISTER_TITLE;
						this.builder = new org.eclipse.cosmos.provisional.dr.ps.components.widget.RegisterDialog(
								{	callback: callbackMethod, 
									statusService: _self.statusService, 
									brokerService:_self.brokerService, 
									labelQuery:_self.labelDialogQuery, 
									title:dialogTitle, 
									epr:registerEPR,
									queryepr:queryEPR,
									UIContext:_self.UIContext,
									listOfMDRs:queryResponse,
									mode:_self.mode});
						this.builder.show();
						
						
					}, queryProp:"query"}
			);
			
			

		},
		render: function(input){
			this.builder.destroy();
			this.builder = null;
			return input;
		},
		
		
		destroy: function()
		{
			this.destroyWidgets(
					["reglabel", "registerGrid", 
			         "regbutton", "regcancel"]);
		}
	}
); 

 dojo.declare(
	"org.eclipse.cosmos.provisional.dr.ps.components.widget.RegisterDialog",
	[dijit._Widget, dijit._Templated, dijit._Container, org.eclipse.cosmos.provisional.dr.ps.components.utility.BasicUtility], 
	{
	 	rows:12,
	 	cols:80,
		labelQuery:"",
		dialogIcon:"",
		_message: dojo.i18n.getLocalization("nls.org.eclipse.cosmos.provisional.dr.ps.components", "widget"),
		templatePath:dojo.moduleUrl("org.eclipse.cosmos.provisional.dr.ps.components.widget", "html/RegisterDialog.html"),
		widgetsInTemplate: true,
		widgetId: "registerDialog",
		gridWidget: null,
		mdrlist: null,
		cmdbfEPR: null,
		queryEPR: null,
		mdrEPRs: null,		
		listOfMDRs: null,
		mode:true,
		
		create: function(params, srcNodeRef) {
			//summary: inherited class from dijit._Widget
				//for some reason I need to destroy widget explicitly
	   			if (dijit.byId(this.widgetId) != null)
	   				dijit.byId(this.widgetId).destroy();
				this.inherited(arguments);
		},			
		show: function(){
			this.dialogBox.show();
			
			gridWidget = dijit.byId("registerGrid");
			mdrlist = this.listOfMDRs;
			
            // define the grid view with columns 
            var regview = {
                    cells: [
                            [{name: ' ', field: -1, width: "16px"}, {name: this._message.REGISTER_MDR, field: 0, width: "320px"}]
                    ]
            };
            // define the grid layout containing the view
            var reglayout = [ regview ];
			
			// create a model from the outputter JSON response 
			var regmodel = new dojox.grid.data.Table(null, this.listOfMDRs);
			
			//gridWidget.autoHeight = true;	// turn on autoHeight
			gridWidget.autoWidth = true;	// turn on autoWidth

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

			// set the grid layout
			gridWidget.setStructure(reglayout);
			
			gridWidget.onStyleRow = function (inRow)
			{
				with (inRow) {											
					
					var NODE_CLASS_INDEXT = 2;
					if (mdrlist[inRow.index][NODE_CLASS_INDEXT] == null)
					{
						return;
					}
					
					var cssClass = mdrlist[inRow.index][NODE_CLASS_INDEXT] + "InRegistrationIcon"; 						
					customClasses += ' ' + cssClass;
					
					if (selected)
					{
						customClasses += " registrationSelected";
					}							
				}
				
			};
		
			// redraw the grid
			gridWidget.render();
		},
		
		
		destroy: function()
		{
			this.destroyWidgets(
					["reglabel", "registerGrid", 
			         "regbutton", "regcancel"]);

			if (this.dialogBox)
			{
				this.dialogBox.onCancel();
			}
		},
	
		
		onRegister: function()
		{
			// summary: This method is connected with the onClick event of the 
			// Register/Deregister button.
			
			var selection = gridWidget.selection.getSelected();
			if ( gridWidget.selection.getSelectedCount() <= 0 )
			{
				alert(this._message.REGISTER_ERROR_NO_SELECTION);
				return;
			}
			
			
			// Build the selected MDR EPRs parameters for the outputter		
			this.mdrEPRs = "";
			for(var i=0, l=selection.length; i<l; i++)
			{
				var index = selection[i];
				var mdr = mdrlist[index];
				this.mdrEPRs += "&mdrEPR" + i + "=" + mdr[1];
			}
			
			// Destroy the registration dialog and show the register response dialog
			this.destroy();
			
			var dialogTitle = this.mode ? this._message.REGISTER_RESPONSE_TITLE : this._message.DEREGISTER_RESPONSE_TITLE;
			var regResponse = new org.eclipse.cosmos.provisional.dr.ps.components.widget.RegisterResponseDialog(
					{	statusService:this.statusService,
						brokerService:this.brokerService, 
						title:dialogTitle,	
						storeURL:this.statusService+(this.mode ? "" : "&deregister=true")+"&cmdbfEPR="+this.cmdbfEPR + "&queryEPR="+this.queryEPR + this.mdrEPRs,
						rootLabel: dialogTitle,
						mode:this.mode,
						closeCaption: this._message.COMMON_CLOSE});
			regResponse.show();
			
		},
		
		onCancel: function(){
			var regcancel = dijit.byId("regcancel");
			regcancel.destroy();

			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).
			this.dialogIcon = this.mode ? "<span class='dialogRegisterWinIcon'></span>" : "<span class='dialogDeRegisterWinIcon'></span>";
				//call superclass
			org.eclipse.cosmos.provisional.dr.ps.components.widget.RegisterDialog.superclass.postMixInProperties.apply(this, arguments);
		},
		
		postCreate: function()
		{		
			//call superclass
			org.eclipse.cosmos.provisional.dr.ps.components.widget.RegisterDialog.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.cmdbfEPR = this.epr;
			this.queryEPR = this.queryepr;
			
			var regbutton = dijit.byId("regbutton");
			regbutton.setLabel(this.mode ? this._message.REGISTER_LBL : this._message.DEREGISTER_LBL);
			regbutton.style.width = "50px";
			
			var regcancel = dijit.byId("regcancel");
			regcancel.setLabel( this._message.CANCEL );
			regcancel.style.width = "50px";
			
			var reglabel = document.getElementById("reglabel");
			reglabel.textContent = this.mode ? this._message.REGISTER_DLG_COMMENT_0 + this._message.REGISTER_DLG_COMMENT_1 :
				this._message.REGISTER_DLG_COMMENT_0 + this._message.DEREGISTER_DLG_COMMENT_0;
			
			dojo.connect(this.dialogBox.closeButtonNode,"onclick", this, "destroy");
		}
	}
);      