package info.bukova.isspst.ui;

import info.bukova.isspst.data.DataModel;
import info.bukova.isspst.services.Service;
import info.bukova.isspst.services.ValidationException;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zul.Constraint;

public class ServiceConstraint<T extends DataModel> implements Constraint {
	
	private Service<T> service;
	private T dataBean;
	
	@Override
	public void validate(Component component, Object value)
			throws WrongValueException {

		String id = component.getId();
		if (id == null || id.isEmpty()) {
			return;
		}
		
		try {
			BeanUtils.setProperty(dataBean, id, value);
			service.validate(dataBean);
		} catch (ValidationException e) {
			Map<String, String> errMessages = e.getMessages();
			
			if (errMessages != null && errMessages.get(id) != null && !errMessages.get(id).isEmpty()) {
				WrongValueException ex = new WrongValueException(component, errMessages.get(id)); 
				throw ex;
			}
		} catch (IllegalAccessException e) {
			
		} catch (InvocationTargetException e) {
			
		}
	}

	public void setService(Service<T> service) {
		this.service = service;
	}

	public void setDataBean(T dataBean) {
		this.dataBean = dataBean;
	}

}
