define([
    "dojo/_base/declare",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin",
    "dojo/_base/lang",
    "dojo/_base/array",
    "dojo/dom-construct",
    "chy/widget/GridHeader",
    "chy/widget/GridRow",
    "chy/store/instanceStore",
    "dijit/registry",
    "dojo/text!./templates/GridBase.html",
    "dijit/form/ValidationTextBox",
    "dijit/form/NumberTextBox"
], function(declare, _WidgetBase, _TemplatedMixin,_WidgetsInTemplateMixin, lang,array, domConstruct, header, girdRow,instanceStore,reg,template) {

    return declare([_WidgetBase, _TemplatedMixin,_WidgetsInTemplateMixin], {
        templateString: template,
        headers:new Array(),
		rowObj:new Array(),
        headerObj:new Array(),
        headerClass: "tableheader",
        store:null,
        url:"",
        lastRow:0,
        deleted:new Array(),
		readonly: true,
        
		constructor: function(args){
			//console.log("Grid construct ",this.id);
            declare.safeMixin(this,args);
			this.headers = new Array();
			this.deleted = new Array();
			this.headers = new Array();
			this.rowObj = new Array();
			this.headerObj = new Array();
			lastRow = 0;
            var _this=this;            
		},
		
		startup: function(){
			console.log("Grid startup ",this.id);
			this.inherited(arguments);
			var _this=this;
			this.store=new instanceStore({url:this.url,callback:function(){
				console.log("store",_this.store);
                _this.setHeaders();
				_this.render();
                _this.setRows();           	
            }});
			if(this.readonly){
				domConstruct.destroy("grid_icons");
			}
		},
        
        render: function(){
        	var _this=this;
        	//create headers
			var obj=new header();
			//console.log('grid render',obj.domNode,_this.headerNode);
			domConstruct.place(obj.domNode,_this.headerNode,"last");
        	array.forEach(this.headers,function(item){
        		var obj=new header(item);
        		domConstruct.place(obj.domNode,_this.headerNode,"last");
        		obj.startup();
        		_this.headerObj.push(obj);
        	});
        },
        addRow:function(item){
    		var obj=new girdRow(item,this.store.data.context.context_id,this.readonly,this.id,this.store.data.context.parent_context_id,this.formid);
    		domConstruct.place(obj.domNode,this.bodyNode,"last");
    		obj.startup();
    		this.rowObj[item.instance_id]=obj;
        },
        removeRow:function(item,instance_id){
        	this.deleted.push({P_INSTANCE_ID:instance_id});
        	this.rowObj[instance_id].destroy();
        	delete this.rowObj[instance_id];
        },
        addChild:function(){
        	this.lastRow++;
        	var data={};
        	array.forEach(this.headers,function(field){
        		data[field.field]=null;
        	});
        	this.addRow({
				instance_id:"N"+this.lastRow,
				row_id:this.name+".N"+this.lastRow,
				subject_id:this.store.data.context.subject_id,
				data:data
			});
        },
        
        setHeaders:function(){
        	var _this=this;
        	array.forEach(this.store.data.context.attrs,function(item){
        		var header={
       				label:item.question_text,
       				field:item.question_id,
       				typetype:item.display_type.code,
       				validation:item.display_type.validation
        		};
        		_this.headers.push(header);
        	});
        },
        setRows:function(){
        	var _this=this;
			array.forEach(this.store.data.context.instances,function(instance){
				var obj=new girdRow(instance,_this.store.data.context.context_id,_this.readonly,_this.id,_this.store.data.context.parent_context_id,_this.formid);
				domConstruct.place(obj.domNode,_this.bodyNode,"last");
				_this.rowObj[instance.instance_id]=obj;
				obj.startup();
			});
        },
        
        doPost: function(){
			var _this = this;
			//delete
			array.forEach(this.deleted,function(item){
				var xhrArgs = {
				  url: "cheyenne?cddid=xam.instance_delete",
				  postData: "cntx="+_this.store.data.cntxt+"&P_INSTANCE_ID="+item.P_INSTANCE_ID+"&STEP_BACK=1&target=delete",
				  handleAs: "text",
				  error: function(error){
					console.error("Cthulhu",error);
				  }
				};
				var deferred = dojo.xhrPost(xhrArgs);
			});
			//add/edit
			/*for (var key in this.rowObj){
        		var row=this.rowObj[key];
				var xhrArgs = {
				  url: "cheyenne?cddid=xam.instance_addedit",
				  postData: "P_CONTEXT_ID="+this.store.data.context.context_id+"&P_SUBJECT_ID="+row.subject_id+"&cntx="+this.store.data.cntxt+"&target=save_and_next",
				  handleAs: "text",
				  error: function(error){
					console.error("Cthulhu",error);
				  }
				};
				console.log('Save row', row);
				if (key.indexOf('N')==0){
    				xhrArgs.postData += "&ACTION_F=add&P_INSTANCE_ID="+this.store.data.context.instance_id;
    			} else {
					xhrArgs.postData += "&ACTION_F=edit&P_INSTANCE_ID="+row.instance_id;
				}
				array.forEach(row.domNode.childNodes,function(node){
					if(node.nodeName.toLowerCase() == "input" || node.nodeName.toLowerCase() == "select"){
						xhrArgs.postData += "&FORM_F="+node.value;
					}
					if(node.nodeName.toLowerCase() == "td"){
						var fields = node.getElementsByTagName("input");
						array.forEach(fields,function(field){
							if(field.name){
								xhrArgs.postData += "&"+field.name+"="+field.value;
							}
						});
						fields = node.getElementsByTagName("select");
						array.forEach(fields,function(field){
							if(field.name){
								xhrArgs.postData += "&"+field.name+"="+field.value;
							}
						});
					}
				});
				var deferred = dojo.xhrPost(xhrArgs);
			}*/
			return true;
        },
		
		destroy: function(preserveDom){
			for (var key in this.rowObj){
				//console.log('destroy',this.rowObj[key]);
        		this.rowObj[key].destroy(preserveDom);
			}
			this.inherited(arguments);
		}
    });

});

function gridDoPost(id){
	require(['dijit/registry'],function(reg){
		var gridWidget = reg.byId(id);
		gridWidget.doPost();
		//gridWidget.destroyRecursive(false);
	});
	return true;
};
