define([
	"dojo/_base/declare",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
	"dojo/parser", 
	"dojo/ready", 
    "dojo/dom",
	"dojo/_base/xhr",
	"dojo/dom-construct",
	"dojo/_base/array",
	"dojo/dnd/Source",
	"dojo/on",
	"dijit/registry",
	"chy/widget/LayouteditorBlock",
	"chy/widget/LayouteditorMovable",
	"dojo/text!./templates/Layouteditor.html"	
], function(declare, _WidgetBase, _TemplatedMixin, parser, ready, dom, xhr, domConstruct, array, Source, on, registry, LayouteditorBlock, LayouteditorMovable, template) {
	return declare("widget.Layouteditor",[_WidgetBase, _TemplatedMixin], {
		//properties
		templateString: template,
		blocks:new Array(),
		contextid: '0',
		layout: 'dummy.xml',
		name: 'Context name',
		contextInfo: null,
		
		//constructor
		constructor: function(args){
			console.log("Load Layouteditor",args);
			declare.safeMixin(this,args);
			var _this=this;
			
			//get contextinfo
			var results = xhr("GET", {
				url: 'cheyenne?cddid=xam.json.context_info&cmode=json&P_CONTEXT_ID='+this.contextid,
				handleAs: "json",
				sync: true,
				error: function(error){console.error("Cthulhu",error);}
			}).then(function(result){
				_this.contextInfo = result;
				console.log("Layouteditor for context "+_this.contextid, _this.contextInfo);
			});
			this.name = this.contextInfo.context.name;
		},
		
		postCreate:function(){
			this.inherited(arguments);
			var _this=this;
			
			//get layout
			var results = xhr("GET", {
				url: this.layout,
				handleAs: "xml",
				preventCache: true,
				error: function(error){console.error("Cthulhu",error);}
			}).then(function(result){
				_this.layoutDom = result;
				array.forEach(result.documentElement.childNodes,function(layoutConfigNode){
					if(layoutConfigNode.localName == 'block'){
						var blockIndex = _this.blocks.length;
						_this.blocks[blockIndex] = new LayouteditorBlock({layoutConfigNode: layoutConfigNode, contextInfo: _this.contextInfo});
						domConstruct.place(_this.blocks[blockIndex].domNode,_this.body,"last");
					}
				});
				
				array.forEach(_this.contextInfo.context.attrs, function(attr){
					 var movable = new LayouteditorMovable({
						questionId: attr.question_id, 
						questionInfo: attr
					});
					domConstruct.place(movable.domNode,_this.questionContainer,"last");
				});
				parser.parse();
				_this.dndSource.sync();
			});
			
			this.exportLayoutXmlButton.thisLayoutEditor = this;
			on(this.exportLayoutXmlButton,"click",function(e){
				var xmlcontent = (new XMLSerializer()).serializeToString(this.thisLayoutEditor.layoutDom);
				xhr("POST", {
					url: "cheyenne?cddid=admin.layouteditor",
					content:{
						P_CONTEXT_ID: this.thisLayoutEditor.contextid,
						target: 'save',
						XMLCONTENT: xmlcontent
					},
					handleAs: "text",
					error: function(error){
						console.error("Cthulhu",error);
						alert('Error while saving layout.\n'+error);
					}
				}).then(function(data){				
					alert("Layout has been saved.");
				});
			});
			
			this.addBlockButton.thisLayoutEditor = this;
			on(this.addBlockButton, "click", function(e){
				var cellLayoutConfigNode = this.thisLayoutEditor.layoutDom.createElementNS("http://www.innovationinvestments.nl/layout","xl:block");
				cellLayoutConfigNode.setAttribute('title','<b>Title</b>');
				cellLayoutConfigNode.setAttribute('type','titlepane');
				cellLayoutConfigNode.setAttribute('open','true');
				cellLayoutConfigNode.setAttribute('toggleable','false');
				this.thisLayoutEditor.layoutDom.documentElement.appendChild(cellLayoutConfigNode);
				var blockIndex = this.thisLayoutEditor.blocks.length;
				this.thisLayoutEditor.blocks[blockIndex] = new LayouteditorBlock({layoutConfigNode: cellLayoutConfigNode, contextInfo: this.thisLayoutEditor.contextInfo});
				domConstruct.place(this.thisLayoutEditor.blocks[blockIndex].domNode,this.thisLayoutEditor.body,"last");
				parser.parse();
			});
			
			this.dndSource = new Source(this.questionContainer, 
				{ 
					singular: true,
					thisLayoutEditor: this,
					copyState: function(keyPressed){
						return false;
					},
					onDrop: function(source, sourceNodes, copy){
						if(this == source){
							return;
						}
						
						var target = this;
						target.onDropExternal(source, sourceNodes, copy);
						target.sync();						
												
						//place layouteditor obj references
						source.thisCell.movable = null;
						
						//update xmldomconfig
						source.thisCell.layoutConfigNode.setAttribute('id',-1);
						
						//update htmlField
						source.thisCell.setHTMLField();
					}
				}					
			);
		},
		
		onStart: function(){
			this.inherited(arguments);
			
			parser.parse();
		},
		
		destroy:function(){
			this.inherited(arguments);
		}
	});
});	
