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

	,tpvOrder: null
	,tpvStatus: null

	,check() {
		this.tpvOrder = this.hash.$.tpvOrder;
		this.tpvStatus = this.hash.$.tpvStatus;

		if (this.tpvStatus) {
			const query = 'CALL myTpvTransaction_end(#transaction, #status)';
			this.conn.execQuery(query, {
				transaction: this.tpvOrder,
				status: this.tpvStatus
			});
		}

		return this.tpvStatus;
	}

	,async pay(amount, company) {
		await this._realPay(amount * 100, company);
	}

	,async _realPay(amount, company) {
		if (!isNumeric(amount) || amount <= 0)
			throw new UserError(_('AmountError'));

		let json;
		
		try {
			json = await this.conn.send('tpv/transaction', {
				amount: parseInt(amount)
				,urlOk: this._makeUrl('ok')
				,urlKo: this._makeUrl('ko')
				,company: company
			});
		} catch(err) {
			throw new UserError(_('PayError'));
		}

		const postValues = json.postValues;

		const form = document.createElement('form');
		form.method = 'POST';
		form.action = json.url;
		document.body.appendChild(form);
		
		for (var field in postValues) {
			const input = document.createElement('input');
			input.type = 'hidden';
			input.name = field;
			form.appendChild(input);
			
			if (postValues[field])
				input.value = postValues[field];
		}
		
		form.submit();
	}
	
	,async retryPay() {
		const query = 'SELECT t.amount, m.companyFk '
			+'FROM myTpvTransaction t '
			+'JOIN tpvMerchant m ON m.id = t.merchantFk '
				+'WHERE t.id = #transaction';

		const res = await this.conn.execQuery(query,
			{transaction: parseInt(this.tpvOrder)});
		const payment = res.fetchObject();
		await this._realPay(payment.amount, payment.companyFk);
	}

	,_makeUrl(status) {
		let path = location.protocol +'//'+ location.hostname;
		path += location.port ? ':'+ location.port : '';
		path += location.pathname;
		path += location.search ? location.search : '';
		path += this.hash.make({
			form: 'ecomerce/orders',
			tpvStatus: status,
			tpvOrder: '_transactionId_'
		}, true);
		return path;
	}
});

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