package com.zi.mwms.solution.config;

import javax.annotation.Resource;

import com.cim.idm.framework.autoconfigure.ZidmPlatformProperties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

import com.cim.idm.flowpackage.core.BpelProcessManager;
import com.cim.idm.framework.fos.idmflow.BpelExRepository;
import com.zi.mwms.solution.Application;
import com.zi.mwms.solution.workflow.CustomBpelExRepository;
import com.zi.mwms.solution.workflow.CustomEventAdaptor;
import com.zi.mwms.solution.workflow.expression.CustomExpression;

@Configuration
@ImportResource(locations="classpath:/service/bpelexecutor.service.xml")
public class WorkflowConfig {

	@Resource
    private ZidmPlatformProperties properties;
	
	@Bean(name="CustomExpression")
	public CustomExpression getCustomExpression() {
		return new CustomExpression();
	}
	
	@Bean(name="BpelExRepository",initMethod="init" )
	public CustomBpelExRepository getBpelExRepository(BpelProcessManager bpelProcessManager) throws Exception {
		CustomBpelExRepository bpelExRepository = new CustomBpelExRepository();
		bpelExRepository.setBpelProcessManager(bpelProcessManager);
		bpelExRepository.setUseBpelsInInnerDirs(true);
		if(properties.getBpelConfigLocation().trim().startsWith("classpath:")){ // BPEL 放在工程项目中
			String classFileRootPath = Application.class.getResource("/").getPath();
			String bpelpath= properties.getBpelConfigLocation().trim().split(":")[1];
			if(!classFileRootPath.endsWith("/target/classes/")){
				//BPEL in SpringBoot run jar
				if(classFileRootPath.endsWith("jar!/BOOT-INF/classes!/")){
					// SpringBoot的工程中资源被放在/BOOT-INF/classes/中
					String jarfilePath = classFileRootPath.substring(5,classFileRootPath.length()-"!/BOOT-INF/classes!/".length());
					bpelExRepository.setBpelRootPath(jarfilePath);
					bpelExRepository.setBpelJarEntryPath("/BOOT-INF/classes" +bpelpath);
				}
			}else{ // 采用Eclipse 或者 IDEA 开发环境，BPEL在工程中
				bpelExRepository.setBpelRootPath(classFileRootPath+"../../src/main/resources"+bpelpath);
			}
		}else{ //BPEL放在文件系统中
			bpelExRepository.setBpelRootPath(properties.getBpelConfigLocation());
		}
		return bpelExRepository;
	}
	
	@Bean("BpelExecutionEventAdaptor")
	public CustomEventAdaptor getBpelExecutionEventAdaptor(BpelExRepository  bpelRepository) {
		CustomEventAdaptor bpelExecutionEventAdaptor = new CustomEventAdaptor();
		bpelExecutionEventAdaptor.setBpelRepository(bpelRepository);
		return bpelExecutionEventAdaptor;
	}
}
