package info.bukova.isspst.ui.main.invoicing;

import info.bukova.isspst.data.Invoicing;
import info.bukova.isspst.data.InvoicingItem;
import info.bukova.isspst.services.invoicing.InvoicingService;
import info.bukova.isspst.ui.FormViewModel;

import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.select.annotation.WireVariable;

public class InvoicingForm extends FormViewModel<Invoicing> {
	
	private InvoicingItem selectedItem;
	private int selectedIndex;
	@WireVariable
	private InvoicingService invoicingService;
	
	@Init(superclass = true)
	public void init() {
		selectedIndex = -1;
	}
	
	private void selectItem(InvoicingItem item) {
		if (item != null) {
			selectedItem = item;
			selectedIndex = getDataBean().getItems().indexOf(item);
		} else {
			selectedItem = null;
			selectedIndex = -1;
		}
	}
	
	@Command
	@NotifyChange({"dataBean", "selectedItem", "selectedIndex"})
	public void addItem() {
		InvoicingItem item = new InvoicingItem();
		getDataBean().getItems().add(item);
		selectItem(item);
	}
	
	@Command
	@NotifyChange({"dataBean", "selectedItem", "selectedIndex"})
	public void removeItem(@BindingParam("item") InvoicingItem item) {
		getDataBean().getItems().remove(item);
		selectItem(null);
		calculate();
	}
	
	@Command
	@NotifyChange({"selectedItem", "selectedIndex"})
	public void onFocus(@BindingParam("item") InvoicingItem item) {
		selectItem(item);
	}
	
	@Command
	@NotifyChange("dataBean")
	public void calculate() {
		invoicingService.calculate(getDataBean());
	}

	public InvoicingItem getSelectedItem() {
		return selectedItem;
	}

	public void setSelectedItem(InvoicingItem selectedItem) {
		this.selectedItem = selectedItem;
	}

	public int getSelectedIndex() {
		return selectedIndex;
	}

	public void setSelectedIndex(int selectedIndex) {
		this.selectedIndex = selectedIndex;
	}
	
}
