package com.uas.platform.b2b.manage.page.criteria;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * 逻辑条件表达式 用于复杂条件时使用
 * 
 * @author yingp
 * 
 */
public class LogicalExpression implements CriterionExpression {

	/**
	 * 逻辑表达式中包含的表达式
	 */
	private CriterionExpression[] expressions;

	/**
	 * 运算符
	 */
	private Operator operator;

	public LogicalExpression(CriterionExpression[] expressions, Operator operator) {
		this.expressions = expressions;
		this.operator = operator;
	}

	@Override
	public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
		List<Predicate> predicates = new ArrayList<Predicate>();
		for (int i = 0, len = this.expressions.length; i < len; i++) {
			predicates.add(this.expressions[i].toPredicate(root, query, builder));
		}
		switch (operator) {
		case OR:
			return builder.or(predicates.toArray(new Predicate[predicates.size()]));
		case AND:
			return builder.and(predicates.toArray(new Predicate[predicates.size()]));
		default:
			return null;
		}

	}

}
