
module.exports = class {
	constructor(app) {
		this.app = app;
		let orderId = localStorage.getItem('hederaBasket');
		if (orderId) orderId = parseInt(orderId);
		this.orderId = orderId;
	}
	async checkOrder(orderId) {
		const resultSet = await this.app.conn.execQuery(
			'CALL myOrder_checkConfig(#id)',
			{id: orderId}
		);
		resultSet.fetchValue();
	}
	async check(checkoutContinue) {
		if (this.orderId) {
			return await this.checkRedirect(checkoutContinue);
		} else {
			this.redirect();
			return false;
		}
	}
	async checkRedirect(checkoutContinue) {
		try {
			await this.checkOrder(this.orderId);
			return true;
		} catch(err) {
			if (err.exception == 'Vn.Lib.UserError') {
				switch(err.code) {
				case 'orderConfirmed':
				case 'orderNotOwnedByUser':
					this.constructor.unload();
					await this.redirect();
					break;
				default:
					this.app.hash.setAll({
						form: 'ecomerce/checkout',
						id: this.orderId,
						continue: checkoutContinue
					});
					Htk.Toast.showError(err.message);
				}
				return false;
			} else
				throw err;
		}
	}
	async redirect() {
		const resultSet = await this.app.conn.execQuery(
			'SELECT COUNT(*) > 0 FROM myOrder');
		if (resultSet.fetchValue()) {
			this.app.hash.setAll({form: 'ecomerce/pending'});
			Htk.Toast.showMessage(_('Load an order'));
		} else {
			this.app.hash.setAll({form: 'ecomerce/checkout'});
		}
	}
	async load(orderId) {
		this.loadIntoBasket(orderId);
		if (await this.checkRedirect('catalog'))
			this.app.hash.setAll({
				form: 'ecomerce/catalog'
			});
	}
	loadIntoBasket(orderId) {
		if (this.orderId != orderId) {
			localStorage.setItem('hederaBasket', orderId);
			this.orderId = orderId;
			Htk.Toast.showMessage(_('OrderLoadedIntoBasket'));
		}
	}
	static unload() {
		localStorage.removeItem('hederaBasket');
	}
};

