import './style.scss';

export default new Class({
	Extends: Hedera.Form,
	Template: require('./ui.xml'),

	activate() {
		this.autoStepLocked = true;
		this.$.assistant.stepsIndex = this.agencySteps;

		this.today = new Date();
		this.today.setHours(0, 0, 0, 0);
	},

	onValuesReady() {
		const orderForm = this.$.orderForm;
		const defaultsForm = this.$.defaults;

		if (!(orderForm.ready && defaultsForm.ready))
			return;

		let date;
		const row = orderForm.$ || defaultsForm.$ || {};
		
		if (!date || date.getTime() < (new Date()).getTime()) {
			date = new Date();
			date.setHours(0, 0, 0, 0);

			let addDays = 0;

			switch(date.getDay()) {
				case 6: // Saturday
					addDays += 2;
					break;
				case 0: // Sunday
					addDays++;
					break;
			}

			if (row.deliveryMethod != 'PICKUP')
				addDays++;

			date.setDate(date.getDate() + addDays);
		}

		this.$.lot.assign({
			date,
			method: row.deliveryMethod,
			agency: row.agencyModeFk,
			address: row.addressFk
		});
		this.autoStepLocked = false;
	},
	
	disableButtons(disable) {
		this.$.assistantBar.disabled = disable;
	},

	async onConfirmClick() {
		this.disableButtons(true);
	
		let id = this.$.params.$.id;
		const params = Object.assign({}, this.$.lot.$);

		let query;
		if (id) {
			params.id = id;
			query = 'CALL myOrder_configure(#id, #date, #method, #agency, #address)';
		} else {
			query = 'CALL myOrder_create(@orderId, #date, #method, #agency, #address); SELECT @orderId;';
		}
		
		let resultSet;
		
		try {
			resultSet = await this.conn.execQuery(query, params);
		} finally {
			this.disableButtons(false);
		}

		if (!resultSet.fetchResult())
			return;
	
		let redirect;
		const basket = new Hedera.Basket(this.app);

		if (id) {
			Htk.Toast.showMessage(_('OrderUpdated'));

			switch(this.hash.$.continue) {
				case 'catalog':
					redirect = {form: 'ecomerce/catalog'};
					break;
				default:
					redirect = {form: 'ecomerce/basket'};
					if (id !== basket.orderId)
						redirect.id = id;
			}
		} else {
			basket.loadIntoBasket(resultSet.fetchValue());
			redirect = {form: 'ecomerce/catalog'};
		}

		this.hash.setAll(redirect);
	},

	onCancelClick() {
		if (this.$.params.$.id)
			window.history.back();
		else
			this.hash.setAll({form: 'ecomerce/orders'});
	},
	
	agencySteps: ['method', 'date', 'address', 'agency', 'confirm-delivery'],
	pickupSteps: ['method', 'date', 'address', 'pickup', 'confirm-pickup'],

	isDelivery() {
		return this.$.rgMethod.value != 'PICKUP';
	},

	onMethodChange() {
		this.$.assistant.stepsIndex = this.isDelivery() ?
			this.agencySteps : this.pickupSteps;
		this.onFieldChange();
	},

	methodValidate() {
		if (!this.$.rgMethod.isSelected())
			throw new Error(_('Please select an option'));
	},

	dateShow() {
		Vn.Node.setText(this.$.dateQuestion, this.isDelivery() ?
			_('OrderDateDeliveryQuestion'):
			_('OrderDatePickupQuestion'));
		this.$.calendar.goToSelectedMonth();
	},

	dateValidate() {
		if (!this.$.calendar.value)
			throw new Error(_('Please select a date'));
	},

	addressShow() {
		Vn.Node.setText(this.$.addressQuestion, this.isDelivery() ?
			_('AddressQuestion'):
			_('AddressQuestionPickup'));
	},

	addressValidate() {
		if (this.$.addressForm.row == -1)
			throw new Error(_('Please select an address'));
	},

	agencyShow() {
		this.$.agencies.refresh();
	},

	agencyValidate() {
		if (this.$.agencyCombo.row == -1 && this.isDelivery())
			throw new Error(_('Please select an agency'));
	},

	pickupShow() {
		this.$.warehouses.refresh();
	},

	pickupValidate() {
		if (this.$.warehouseCombo.row == -1)
			throw new Error(_('Please select a store'));
	},
	
	onFieldChange() {
		if (!this.autoStepLocked)
			this.$.assistant.moveNext();
	},
	
	onAddressClick(addressId) {
		this.$.lot.set('address', addressId);
		this.$.assistant.moveNext();
	},
	
	onAddressChange() {
		if (this.selectedNode)
			Vn.Node.removeClass(this.selectedNode, 'selected');

		const row = this.$.addresses.search('id', this.$.lot.$.address);

		if (row != -1) {
			const builder = this.$.repeater.getBuilder(row);
		
			this.selectedNode = builder.$.address;
			Vn.Node.addClass(this.selectedNode, 'selected');
		}

		this.$.addressForm.row = row;
	},
	
	onAgenciesReady(model) {
		this.selectAgency(model, 'NoAgeciesAvailableForDate');
	},
	
	onWarehousesReady(model) {
		this.selectAgency(model, 'NoWarehousesAvailableForDate');
	},

	selectAgency(model, emptyMessage) {
		if (!model.ready) return;
		let agencyId = null;

		if (model.numRows > 0) {
			const agencies = [this.$.lot.$.agency];

			const defaults = this.$.defaults.$ || {};
			if (defaults.agencyModeFk)
				agencies.push(defaults.agencyModeFk);
			if (defaults.defaultAgencyFk)
				agencies.push(defaults.defaultAgencyFk);

			for (const agency of agencies)
			if (model.search('id', agency) !== -1) {
				agencyId = agency;
				break;
			}
		} else
			Htk.Toast.showError(_(emptyMessage));

		this.autoStepLocked = true;
		this.$.lot.assign({agency: agencyId});
		this.autoStepLocked = false;
	},
	
	calendarRestrict(date) {
		return date.getTime() >= this.today.getTime();
	}
});
