package info.bukova.isspst.ui.addressbook;

import info.bukova.isspst.data.Address;
import info.bukova.isspst.services.IsspstException;
import info.bukova.isspst.services.addressbook.AdbService;
import info.bukova.isspst.services.addressbook.AddressFinder;
import info.bukova.isspst.ui.FormViewModel;
import info.bukova.isspst.validators.AddressValidator;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

public class AddressForm extends FormViewModel<Address> {
	
	@WireVariable
	private AdbService adbService;
	@WireVariable
	private AddressFinder addressFinderAres;
	@WireVariable
	private AddressFinder addressFinderTaxID;
	private AddressValidator validator;
			
	@Init(superclass = true)
	public void init() {
		validator = new AddressValidator();
	}
	
	@Command
	@NotifyChange("dataBean")
	public void searchAres() {
		getDataForm().bind();
		
		if (getDataBean().getIc() != 0) {
			try {
				adbService.fillFoundData(addressFinderTaxID, getDataBean());
			} catch (IsspstException e) {
				e.printStackTrace();
			}
			return;
		}
		
		Map<String, List<Address>> arg = new HashMap<String, List<Address>>();
		try {
			arg.put("result", adbService.lookForAddr(addressFinderAres, getDataBean()));
		} catch (IsspstException e) {
			e.printStackTrace();
			Messagebox.show("Chyba při hledání adresy", "Chyba", Messagebox.OK, Messagebox.ERROR);
			return;
		}
		Window resWin = (Window) Executions.createComponents("addrFindResult.zul", null, arg);
		resWin.doModal();
		
	}
	
	@GlobalCommand("selectAddress")
	@NotifyChange("dataBean")
	public void selectAddress(@BindingParam("selected") Address selected, @BindingParam("window") Window window) {
		try {
			adbService.fillFoundData(addressFinderTaxID, selected);
		} catch (IsspstException e) {
			e.printStackTrace();
		}
		
		adbService.mergeAddress(getDataBean(), selected, true);
		
		if (window != null)
			window.detach();
	}

	public AddressValidator getValidator() {
		return validator;
	}
	
}
