define([
    "dojo/_base/declare",
    "dojo/request/xhr",
    "dojo/request/notify",
    "dojo/dom-form",
	"dojo/promise/all"
], function(declare, xhr, notify,domForm,all){
	return declare("chy._base._RequestMixin", null, {
		lastPage:null,
		reqSync:false,
		
		/*constructor : function(args) {
			console.log("_RequestMixin.construct");
			notify("start", function(){
	            console.log("Start");
	        });
	        notify("send", function(data, cancel){
	            console.log("Sent request",cancel);
	        });
	        notify("load", function(data){
	            console.log("Load (response received)",data);
	        });
	        notify("error", function(error){
	            console.log("Error",error);
	        });
	        notify("done", function(data){
	            console.log("Done (response processed)",data);
	        });
	        notify("stop", function(){
	            console.log("Stop");
	        });
		},
		*/
		getContent : function(url,id, callback,onError) {
			var content;
			var _this = this;
			//if (this.lastPage === url) {
			//	return;
			//}
			this.lastPage = url;

			var result=xhr.get(url, {
			// handleAs:'text'
				sync:this.reqSync,
				preventCache:true,
				headers:{'Content-encoding':'UTF-8'},
				error: function(error){console.error("Cthulhu",error);}
			});
			result.response.then(function(response){
				if (response.status==401 || (response.text.indexOf("credentials") !=-1 && response.text.indexOf("<html") !=-1))	{
					window.location.reload(true);
				} else {
					callback(response);
				}
			}, onError);
		},
		
		postContentFiles : function(form) {
			if (typeof FormData == "undefined") {
				return false;
			}
			
			var promises = [];
			
			// Using the HTML5 File API and data-* attributes,
			// post the form to the url specified in the gzm-prepost-url attribute of alle file inputs.
			// Then, the response is handed to the callback function named in gzm-prepost-callback, to
			// check if the upload has succeeded.
			for (var i = 0; i < form.elements.length; i++) {
				var elem = form.elements[i];
				if (elem.type == "file") {
					var url = elem.dataset['gzmPrepostUrl']; // dashed attribute names are converted to CamelCase!
					var callback = window[elem.dataset['gzmPrepostCallback']];
					if (url == undefined || callback == undefined) {
						console.log('No prepost callback; skipping', elem);
						continue;
					}
					var postData=new FormData(form); // send regular form data as well as files
					// FIXME (wanneer we dat gaan gebruiken): meerdere file-inputs op hetzelfde form worden allemaal naar alle urls gestuurd
					// postData.append(elem.name, elem.files[0]); // FormData constructor already adds all files
					console.log('Prepost to', url);
					var result = xhr.post(url, {
						data: postData,
						sync: this.reqSync,
						preventCache:true
					});
					promises.push(result.then(function(response) {
						return callback(response);
					}));
				}
			}
			
			return promises;
		},
		
		postContent : function(form, id,callback,onError){
			var postData=domForm.toObject(form);
			
			var filePromises = this.postContentFiles(form);
			if (filePromises === false) {
				console.warn("Preposting files failed.");
				filePromises = [];
				// TODO signal error/warning to user?
			}
			
			console.log("POST data",form,postData);
			
			all(filePromises).then(function(files) {
				for (var i = 0; i < files.length; i++) {
					if (!files[i]) {
						console.warn("File prepost failed.");
						// TODO signal error/warning to user?
					}
				}
				var result=xhr.post(form.action,{
					data: postData,
					sync:this.reqSync,
					preventCache:true,
					headers:{'Content-encoding':'UTF-8', 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'},
					trgt_id:id,
					error: function(error){console.error("Cthulhu",error);}
				});
				result.response.then(function(response){
					if (response.status==401 || (response.text.indexOf("credentials") !=-1 && response.text.indexOf("<html") !=-1))	{
						window.location.reload(true);
					} else {
						console.log("callback with id",id);
						callback(response);
					}
				}, onError);
			});
		}
		
	});
});