import './style.scss';

const Catalog = new Class({
	Extends: Hedera.Form,
	Template: require('./ui.xml')
	
	,_menuShown: false

	,async open() {
		const basket = new Hedera.Basket(this.app);

		if (!localStorage.getItem('hederaGuest')) {
			if (await basket.check('catalog'))
				this.orderId = basket.orderId;
		} else {
			const resultSet = await this.conn.execQuery(
				'CALL myOrder_configureForGuest(@orderId); SELECT @orderId;');

			resultSet.fetchResult();
			this.orderId = resultSet.fetchValue();
		}

		if (this.orderId)
			await Hedera.Form.prototype.open.call(this);
	}

	,activate() {
		document.body.appendChild(this.$.rightPanel);
		this.$.items.setInfo('i', 'item', 'vn', ['id']);
		this.$.orderLot.assign({orderId: this.orderId});
		
		if (localStorage.getItem('hederaView'))
			this.setView(parseInt(localStorage.getItem('hederaView')));
		else
			this.setView(Catalog.View.GRID);

		this.onFilterChange();
	}
	
	,deactivate() {
		this.hideMenu();
		this.gui.$.topBar.style.backgroundColor = '';
		Vn.Node.remove(this.$.rightPanel);
	}

	,getFilter(params, tags, currentTag) {
		if (params.search == null && params.realm == null)
			return;

		const $ = this.$;

		params = Object.assign({}, params);
		const filter = new Sql.Operation({
			type: Sql.Operation.Type.AND
		});

		let idSearch = false;
		if (params.search != null) {
			idSearch = /^\d+$/.test(params.search);

			if (!idSearch) {
				filter.push($.searchOp);
				params.search = `%${params.search}%`;
			} else
				filter.push($.idOp);
		}

		if (!idSearch) {
			if (params.realm != null)
				filter.push($.realmOp);
			if (params.type != null)
				filter.push($.typeOp);

			for (const tag of tags)
			if (tag != currentTag && params[tag] != null)
				filter.push($[`${tag}Op`]);
		}

		params.filter = filter;
		const lot = new Vn.Lot();
		lot.setAll(params);

		return lot;
	}

	,onFilterChange() {
		const $ = this.$;
		const params = $.params.$;

		this.refreshTitle();
		const hasRealm = params.realm != null;
		$.filters.style.display = hasRealm ? 'block' : 'none';
		$.realmMsg.style.display = hasRealm ? 'none' : 'block';

		const tags = [
			'color',
			'origin',
			'category',
			'producer'
		];

		let hasTagFilter = false;
		for (const tag of tags)
		if (params[tag] != null) {
			hasTagFilter = true;
			break;
		}

		params.orderId = this.orderId;
		const refreshItems = hasTagFilter
			|| params.search != null
			|| params.type != null;

		const lot = refreshItems && this.getFilter(params, tags);
		if (lot) {
			$.items.lot = lot;
			$.items.refresh();
		} else
			$.items.clean();

		for (const tag of tags)
			$[`${tag}s`].lot = this.getFilter(params, tags, tag);

		if (lot) this.hideMenu();
	}
	
	,refreshTitle() {
		const hash = this.hash.$;
		const types = this.$.types;
		const realms = this.$.realms;

		const type = hash.type;
		const realm = hash.realm;
		let typeName;
		let realmName;
		
		if (type && types.ready) {
			var row = types.search('id', type);
			if (row != -1) typeName = types.get(row, 'name');
		}
		if (realm && realms.ready) {
			var row = realms.search('id', realm);
			if (row != -1) realmName = realms.get(row, 'name');
		}

		let title = _('Catalog');
		let subtitle = '';

		if (typeName) {
			title = typeName;
			subtitle = realmName;
		} else if (realmName) {
			title = realmName;
		}

		Vn.Node.setText(this.$.titleText, title);
		Vn.Node.setText(this.$.subtitle, subtitle);
	}
	
	,setView(view) {
		if (view === Catalog.View.GRID) {
			this.$.viewButton.setProperties({
				icon: 'view_list',
				tip: _('List view')
			});
			this.view = Catalog.View.GRID;
			var className = 'grid-view';
		} else {
			this.$.viewButton.setProperties({
				icon: 'grid_on',
				tip: _('Grid view')
			});
			this.view = Catalog.View.LIST;
			var className = 'list-view';
		}
		
		var node = this.$.gridView.node;
		node.className = className;
		localStorage.setItem('hederaView', this.view);
	}
	
	,onSwitchViewClick() {
		this.setView(this.view === Catalog.View.LIST ?
			Catalog.View.GRID : Catalog.View.LIST);
	}
	
	,onItemsChange(model, status) {
		if (status !== Db.Model.Status.CLEAN)
			this.$.order.style.display = 'block';
		else
			this.$.order.style.display = 'none';
	}
	
	,onOrderChange(e) {
		var value = e.target.value;	
		var sortField = value.substr(2);
		var sortWay = value.charAt(0) === 'A' ?
			Db.Model.SortWay.ASC : Db.Model.SortWay.DESC;
		
		if (sortField)
			this.$.items.sortByName(sortField, sortWay);
		
		this.hideMenu();
	}
	
	,realmRenderer(builder, form) {
		var link = builder.$.link;
		link.href = this.hash.make({
			form: this.hash.$.form,
			realm: form.$.id
		});
	}

	,onRightPanelClick(event) {
		event.stopPropagation();
	}

	,onShowMenuClick(event) {
		this._menuShown = true;
		event.stopPropagation();
		this.gui.showBackground();
		Vn.Node.addClass(this.$.rightPanel, 'show');
		this.hideMenuCallback = this.hideMenu.bind(this);
		document.addEventListener('click', this.hideMenuCallback);
	}

	,hideMenu() {
		if (!this._menuShown)
			return;

		this.gui.hideBackground();
		Vn.Node.removeClass(this.$.rightPanel, 'show');
		document.removeEventListener('click', this.hideMenuCallback);
		this.hideMenuCallback = null;
	}
	
	,isGuest() {
		if (localStorage.getItem('hederaGuest')) {
			Htk.Toast.showError(_('YouMustBeLoggedIn'));
			return true;
		}
		
		return false;
	}
	
	,onBasketClick() {
		if (this.isGuest())
			return;

		this.hash.setAll({form: 'ecomerce/basket'});
	}
	
	,onConfigureClick() {
		if (this.isGuest())
			return;

		this.hash.setAll({
			form: 'ecomerce/checkout',
			id: this.orderId,
			continue: 'catalog'
		});
	}

	,onAddItemClick(event, form) {
		if (event.defaultPrevented) return;
		event.preventDefault();
		if (this.isGuest()) return;

		this.onEraseClick();
		this.$.$card.row = form.row;
		this.$.cardLot.assign({
			item: form.$.id,
			orderId: this.orderId
		});
		this.$.cardPopup.show(event.currentTarget);
	}
	
	,onAddLotClick(column, value, row) {
		var model = this.$.itemLots;
		var grouping = model.get(row, 'grouping');
		var warehouse = model.get(row, 'warehouseFk');
		var available = model.get(row, 'available');

		var lotAmount = this.items[warehouse];

		if (lotAmount === undefined)
			lotAmount = 0;
		
		if (lotAmount < available) {
			var newAmount = lotAmount + grouping;
		
			if (newAmount > available)
				newAmount = available;
		
			this.items[warehouse] = newAmount;
			this.$.amount.value += newAmount - lotAmount;
		} else
			Htk.Toast.showError(_('NoMoreAmountAvailable'));
	}
	
	,async onConfirmClick() {
		var sql = '';
		var query = new Sql.String({query: 'CALL myOrder_addItem(#orderId, #warehouse, #item, #amount);'});
		var amountSum = 0;

		for (var warehouse in this.items) {
			var amount = this.items[warehouse];
			amountSum += amount;
		
			const params = {
				orderId: this.orderId,
				warehouse: warehouse,
				item: this.$.cardLot.$.item,
				amount: amount
			}
			sql += query.render(params);
		}
	
		if (amountSum > 0) {
			this.conn.execQuery(sql);

			var itemName = this.$.$card.get('item');
			Htk.Toast.showMessage(
				Vn.Value.sprintf(_('Added%dOf%s'), amountSum, itemName));
		}

		this.$.cardPopup.hide();
	}
	
	,onEraseClick() {
		this.$.amount.value = 0;
		this.items = {};
	}
	
	,onPopupClose() {
		this.onEraseClick();
		this.$.$card.row = -1;
		this.$.cardLot.value = undefined;
	}
	
	,onCardLoad() {
		this.$.cardPopup.reset();
	}
});

Catalog.extend({
	View: {
		LIST: 0,
		GRID: 1
	}
});

export default Catalog;
