package de.florianmarsch.fussballmanager.db.jpa;

import javax.persistence.EntityManager;

import com.mysema.query.BooleanBuilder;
import com.mysema.query.jpa.impl.JPAQuery;
import com.mysema.query.types.PathMetadata;
import com.mysema.query.types.PathMetadataFactory;
import com.mysema.query.types.path.EntityPathBase;
import com.mysema.query.types.path.StringPath;

import de.florianmarsch.fussballmanager.db.entity.AbstractEntity;

public class QueryBuilder {

	private EntityManager em;
	private EntityPathBase<? extends AbstractEntity> source;
	
	public QueryBuilder(EntityManager aEntityManager, EntityPathBase<? extends AbstractEntity> aFrom){
		em = aEntityManager;
		source = aFrom;
	}
	
	public JPAQuery select(BooleanBuilder condition){
		
		JPAQuery tempQuery = new JPAQuery(em).from(source);
		tempQuery.where(buildCondition(condition));
		return tempQuery;
	}

	private BooleanBuilder buildCondition(BooleanBuilder condition) {
		BooleanBuilder finalCondition = null;
		BooleanBuilder schemeCondition = new BooleanBuilder();
		
		PathMetadata<String> forProperty = PathMetadataFactory.forProperty(source, "schemaName");
		   
		
		schemeCondition.and(new StringPath(forProperty).eq( System.getenv("SCHEME")));
		if(condition!= null && condition.hasValue()){
			BooleanBuilder joinCondition = new BooleanBuilder();
			joinCondition.and(condition);
			joinCondition.and(schemeCondition);
			finalCondition = joinCondition;
		}else{
			finalCondition = schemeCondition;
		}
		return finalCondition;
	}
}

@@ -816,31 +816,16 @@
 y.where(
-buildCondition(
 conditio
@@ -826,17 +826,16 @@
 ndition)
-)
 ;%0A%09%09retu
@@ -856,644 +856,6 @@
 %09%7D%0A%0A
-%09private BooleanBuilder buildCondition(BooleanBuilder condition) %7B%0A%09%09BooleanBuilder finalCondition = null;%0A%09%09BooleanBuilder schemeCondition = new BooleanBuilder();%0A%09%09%0A%09%09PathMetadata%3CString%3E forProperty = PathMetadataFactory.forProperty(source, %22schemaName%22);%0A%09%09   %0A%09%09%0A%09%09schemeCondition.and(new StringPath(forProperty).eq( System.getenv(%22SCHEME%22)));%0A%09%09if(condition!= null && condition.hasValue())%7B%0A%09%09%09BooleanBuilder joinCondition = new BooleanBuilder();%0A%09%09%09joinCondition.and(condition);%0A%09%09%09joinCondition.and(schemeCondition);%0A%09%09%09finalCondition = joinCondition;%0A%09%09%7Delse%7B%0A%09%09%09finalCondition = schemeCondition;%0A%09%09%7D%0A%09%09return finalCondition;%0A%09%7D%0A
 %7D%0A

remove unused scheme