var DBG = DBG || false

function p5UI__ButtonAjax(n, eventNamespace, props) {
	var eventNamespace = eventNamespace || 'p5UI__ButtonAjax';
	var $n = jQuery(n);
	var state = {
		baseCssClassNames: n.className,
		href: props.href
	};
	jQuery(document).trigger(eventNamespace+':click', [n, state]);
	if ($n.hasClass('disabled')) {// bootstrap already prevent this action
		if(DBG)console.log('WARNING: btn disabled - waiting for response - Cancel?');
		return false;
	}
	$n.removeClass('btn-primary').addClass('btn-default disabled btn-loading');

	var req = superagent
		.post(props.href)
		.type('json') // header ĺapplication/x-www-form-urlencoded' requires type('form');
		.send(props.data)
		.set('Accept', 'application/json')
		.end(function(err, res) {
			if(DBG)console.log('DBG: res:', res, 'res.body:', res.body);
			$n.removeClass('btn-default disabled btn-loading').addClass(state.baseCssClassNames);
			var payload;
			if (err || !res.ok || 'application/json' !== res.type) {
				payload = {type: 'warning', msg: res.body.msg || 'Request error', body: res.body};
			} else {
				payload = {type: res.body.type || 'success', msg: res.body.msg || '', body: res.body};
			}
			jQuery(document).trigger('DBG:notify', payload);
			jQuery(document).trigger(eventNamespace+':ajaxLoaded', [n, payload]);
			req = null;
		});

	// setTimeout(function() {
	// 	console.log('Test click p5UI__ButtonAjax - setTimeOut', $n, state);
	// 	jQuery(document).trigger('p5UI__ButtonAjax:ajaxLoaded', [n, state]);
	// 	$n.removeClass('btn-default disabled btn-loading').addClass(state.baseCssClassNames);
	// }, 1000);
	return false;
}

function p5UI__ajaxLinkClick(n, href, data) {
	if (!n || !href) return true;

	var $n = jQuery(n);
	if ($n.hasClass('disabled')) {// bootstrap already prevent this action
		if(DBG)console.log('WARNING: btn disabled - waiting for response - Cancel?');
		return false;
	}
	$n.removeClass('btn-primary').addClass('disabled btn-loading');

	var req = superagent
		.post(href)
		.type('json') // header ĺapplication/x-www-form-urlencoded' requires type('form');
		.send(data)
		.set('Accept', 'application/json')
		.end(function(err, res) {
			if(DBG)console.log('DBG: res:', res, 'res.body:', res.body);
			$n.removeClass('disabled btn-loading').addClass(state.baseCssClassNames);
			var payload;
			if (err || !res.ok || 'application/json' !== res.type) {
				payload = {type: 'warning', msg: res.body.msg || 'Request error', body: res.body};
			} else {
				payload = {type: 'success', msg: res.body.msg || '', body: res.body};
			}
			if(DBG)console.log('DBG: before p5UI__notifyAjaxCallback:', payload);
			p5UI__notifyAjaxCallback(payload);
			if(DBG)console.log('DBG: before actions:', payload.body.actions);
			if (payload.body.actions) {
				for (i in payload.body.actions) {
					p5UI__execAction(payload.body.actions[i]);
				}
			}
			req = null;
		});
	return false;
}

function p5UI__execAction(action) {
	if(DBG)console.log('DBG: action:', action);
	if ('jsFunction' in action) {
		if (action['jsFunction'] in window) {
			if(DBG)console.log('TODO: exec "window[\''+action['jsFunction']+'\']( '+action['args']+' )"');
			window[ action['jsFunction'] ]( action['args'] );
		}
		else {
			if(DBG)console.log('BUG: jsFunction not exists "'+action['jsFunction']+'"');
		}
	} else {
		if(DBG)console.log('TODO: action', action);
	}
}

function p5UI__notifyAjaxCallback(data) {
	var notify = {};
	notify.type = (data && data.type)? data.type : '';
	notify.msg = (data && data.msg)? data.msg : '';
	switch (notify.type) {
		case 'success':
			if (!notify.msg) notify.msg = 'OK';
			break;
		case 'info':
			if (!notify.msg) notify.msg = '';
			break;
		case 'error':
			if (!notify.msg) notify.msg = 'Wystąpiły błędy';
			break;
		case 'warning':
			notify.type = 'warn';
			if (!notify.msg) notify.msg = 'Wystąpiły błędy';
			break;
		default:
			notify.msg = 'Nieznany błąd';
			if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
			notify.type = '';
	}
	jQuery.notify(notify.msg, notify.type);
}

global.p5UI__ButtonAjax = p5UI__ButtonAjax
global.p5UI__ajaxLinkClick = p5UI__ajaxLinkClick
global.p5UI__execAction = p5UI__execAction
global.p5UI__notifyAjaxCallback = p5UI__notifyAjaxCallback
