
module.exports = new Class
({
	Extends: Vn.Object

	,tpvOrder: null
	,tpvStatus: null

	,check: function (callback)
	{
		this.tpvOrder = this.hash.get ('tpvOrder');
		this.tpvStatus = this.hash.get ('tpvStatus');

		if (this.tpvStatus)
		{
			var query = 'CALL transactionEnd (#transaction, #status)';
			var params = {
				transaction: this.tpvOrder,
				status: this.tpvStatus
			};
			this.conn.execQuery (query, null, params);
		}
		
		if (callback)
			callback (this, this.tpvOrder, this.tpvStatus);
	}

	,pay: function (amount, company)
	{
		this._realPpay (amount * 100, company);
	}

	,_realPpay: function (amount, company)
	{	
		if (isNumeric (amount) && amount > 0)
		{
			var params = {
				 amount: parseInt (amount)
				,urlOk: this._makeUrl ('ok')
				,urlKo: this._makeUrl ('ko')
				,company: company
			};
		
			this.conn.send ('tpv/transaction', params,
				this._onTransactionStart.bind (this));
		}
		else
			Htk.Toast.showError (_('AmountError'));
	}

	,_onTransactionStart: function (json)
	{
		if (json)
		{
			var postValues = json.postValues;

			var form = document.createElement ('form');
			form.method = 'post';
			form.action = json.url;
			document.body.appendChild (form);

			for (var field in postValues)
			{
				var input = document.createElement ('input');
				input.type = 'hidden';
				input.name = field;
				form.appendChild (input);
				
				if (postValues[field])			
					input.value = postValues[field];
			}
			
			form.submit ();
		}
		else
			Htk.Toast.showWarning (_('PayError'));
	}
	
	,retryPay: function ()
	{
		var query = 'SELECT t.amount, m.company_id '
			+'FROM tpv_transaction_view t '
			+'JOIN tpv_merchant m ON t.merchant_id = m.id '
				+'WHERE t.id = #transaction';
		var params = {transaction: parseInt (this.tpvOrder)};
		this.conn.execQuery (query,
			this._onRetryPayDone.bind (this), params);
	}
	
	,_onRetryPayDone: function (resultSet)
	{
		var row = resultSet.fetchObject ();
		
		if (row)
			this._realPpay (row.amount, row.company_id);
		else
			Htk.Toast.showError (_('AmountError'));
	}

	,_makeUrl: function (status)
	{
		var path = location.protocol +'//'+ location.host;
		path += location.port ? ':'+ location.port : '';
		path += location.pathname;
		path += location.search ? location.search : '';
		path += this.hash.make ({
			'form': 'ecomerce/orders',
			'tpvStatus': status,
			'tpvOrder': '%s'
		}, true);

		return path;
	}
});

function isNumeric (n)
{
	return !isNaN (parseFloat(n)) && isFinite (n);
}
