package ${entity.getPackage('service.impl')} ;

import java.io.*;
import java.util.*;

import org.asyrinx.brownie.core.query.exp.IExpression;

import ${entity.getPackage('entity')}.*;
import ${entity.getPackage('dao')}.*;
import ${entity.getPackage('service')}.*;
####
#set( $refEntitySet = ${entity.getReferenceEntitiesAll()} )
#foreach( $refEntity in ${refEntitySet} )
import ${refEntity.getPackage('dao')}.*;
#end

/** 
 *
#if ($addTimeStamp)
 * [$now]
#end
 */
#set( $daoClassName = "${daoPrefix}${entity.getName()}${daoSuffix}" )
#set( $daoPropName = ${stringUtils.uncapitalize($daoClassName)} )
#set( $serviceIntfClassName = "${servicePrefix}${entity.getName()}${serviceSuffix}" )
#set( $serviceImplClassName = "${serviceImplPrefix}${entity.getName()}${serviceImplSuffix}" )
public class ${serviceImplClassName} implements ${serviceIntfClassName}  {
	public ${serviceImplClassName}(${daoClassName} ${daoPropName}
####
#foreach( $refEntity in ${refEntitySet} )
#set( $refDao = "${daoPrefix}${refEntity.getName()}${daoSuffix}" )
#set( $refDaoProp = ${stringUtils.uncapitalize($refDao)} )
	        ,${refDao} ${refDaoProp}
#end
	){
		super();
		this.${daoPropName} = ${daoPropName};
#foreach( $refEntity in ${refEntitySet} )
#set( $refDao = "${daoPrefix}${refEntity.getName()}${daoSuffix}" )
#set( $refDaoProp = ${stringUtils.uncapitalize($refDao)} )
	    this.${refDaoProp} = ${refDaoProp};
#end
	}
	
	protected final ${daoClassName} ${daoPropName};

#foreach( $refEntity in ${refEntitySet} )
#set( $refDao = "${daoPrefix}${refEntity.getName()}${daoSuffix}" )
#set( $refDaoProp = ${stringUtils.uncapitalize($refDao)} )
	protected final ${refDao} ${refDaoProp};
#end

	public void save(${entity.getName()} obj) {
		prepareReferences(obj);
		${daoPropName}.save(obj);
	}

	public void delete(${entity.getName()} obj) {
		${daoPropName}.delete(obj);
	}

	public ${entity.getName()} load(Serializable key) {
		return ${daoPropName}.load(key);
	}

    public List select(IExpression expression) {
		return ${daoPropName}.select(expression);
	}
	
    public void prepareReferences(${entity.getName()} obj) {
#foreach( $ref in ${entity.getReferencesAll()} )
#set( $refEntity = ${ref.getReferenceClass()} )
#set( $refDao = "${daoPrefix}${refEntity.getName()}${daoSuffix}" )
#set( $refDaoProp = ${stringUtils.uncapitalize($refDao)} )
#set( $refProp = ${ref.getPropertyNameInLocal()} )
#set( $refPropCap = ${stringUtils.capitalize($refProp)} )
        if (obj.get${refPropCap}Key() != null) {
            if ((obj.get${refPropCap}() == null)
                    || !obj.get${refPropCap}().getPrimaryKey().equals(obj.get${refPropCap}Key()))
                obj.set${refPropCap}(${refDaoProp}.load(obj.get${refPropCap}Key()));
        }
#end
    }

}
