package com.axelor.meta.views;

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

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

import com.axelor.meta.ActionHandler;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

@XmlType
public class ActionCondition extends Action {

	@XmlElement(name = "check")
	private List<Check> conditions;
	
	@Override
	public Object evaluate(ActionHandler handler) {
		Map<String, String> errors = Maps.newHashMap();
		for(Check check : conditions) {
			if (check.test(handler)) {
				errors.put(check.getField(), check.getError());
			}
		}
		return errors;
	}

	@Override
	public Object wrap(ActionHandler handler) {
		return ImmutableMap.of("errors", evaluate(handler));
	}
	
	@XmlType
	public static class Check extends Act {
		
		@XmlAttribute
		private String field;
		
		@XmlAttribute
		private String error;
		
		@Override
		public String getCondition() {
			String condition = super.getCondition();
			if (isEmpty(condition) && !isEmpty(field)) {
				return field + " == null";
			}
			return condition != null ? condition.trim() : condition;
		}
		
		public String getField() {
			return field;
		}
		
		public String getError() {
			if (isEmpty(error)) {
				if (isEmpty(super.getCondition())) {
					return "Field is required.";
				}
				return "Invalid field value.";
			}
			return error;
		}
		
		private boolean isEmpty(String str) {
			return str == null || "".equals(str.trim());
		}
		
		@Override
		public String toString() {
			return Objects.toStringHelper(getClass())
					.add("field", field)
					.add("error", getError())
					.add("condition", getCondition())
					.toString();
		}
	}
}

@@ -641,35 +641,143 @@
 %0A%09%09%09
-if (check.test(handler
+for (String field : check.getField().split(%22,%22)) %7B%0A%09%09%09%09field = field.trim();%0A%09%09%09%09if (check.test(handler,check.getCondition(field)
 )) %7B%0A
+%09
 %09%09%09%09
@@ -787,32 +787,21 @@
 ors.put(
-check.getF
+f
 ield
-()
 , check.
@@ -816,17 +816,27 @@
 ());%0A%09%09%09
-%7D
+%09%7D%0A%09%09%09%7D%0A%09%09%09
 %0A%09%09%7D%0A%09%09r
@@ -1105,36 +1105,24 @@
 g error;%0A%09%09%0A
-%09%09@Override%0A
 %09%09public Str
@@ -1138,16 +1138,28 @@
 ndition(
+String field
 ) %7B%0A%09%09%09S

Support for multi fields in ActionCondition