package com.eactive.eai.rms.common.datasource;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
//@DeclarePrecedence("TransactionLoggingAspect,RoutingDataSourceService+, AnnotationTransactionAspect, *")  //AOP Áö¿ø¾ÈÇÔ.
public class RoutingDataSourceService {

//    @Pointcut("(" + "execution (* com.eactive.eai.rms.onl.common.service.EaiServerInfoService+.getEaiServerIpList*(..))\n" +
//            "|| execution (* com.eactive.eai.rms.onl.common.service.EaiServerInfoService+.getHostServerIpList(..))\n" +
//            "|| execution (* com.eactive.eai.rms.onl.common.service.DashboardTargetService+.getBatchProcCount*(..))\n" +
//            "|| execution (* com.eactive.eai.rms.onl.common.service.DashboardTargetService+.getEaiBatchServerIpList(..))\n" +
//            ")" + "&& args(service, ..)")
//    public void service(String service) {}
//
//    @Around(value = "com.eactive.eai.rms.common.datasource.RoutingDataSourceService.service(service)")
//    public Object aroundService(ProceedingJoinPoint joinPoint, String service) {
//
//        Object returnValue = null;
//
//        DataSourceType originalDataSourceType = DataSourceContextHolder.getDataSourceType();
//
//        DataSourceType currentDataSourceType = DataSourceTypeManager.getDataSourceType(service);
//        try {
//            DataSourceContextHolder.setDataSourceType(currentDataSourceType);
//            returnValue = joinPoint.proceed(new Object[]{currentDataSourceType.getSchema()});
//        } catch (Throwable throwable) {
//            throwable.printStackTrace();
//        } finally {
//            DataSourceContextHolder.setDataSourceType(originalDataSourceType);
//        }
//
//        return returnValue;
//    }

    @Around(value = "execution(* SpecifiedDataSourceExecutor.doExecute()) && this(executor)")
    public Object aroundService(ProceedingJoinPoint joinPoint, SpecifiedDataSourceExecutor executor) {
        Object returnValue = null;
        DataSourceType originalDataSourceType = DataSourceContextHolder.getDataSourceType();

        try {
            DataSourceContextHolder.setDataSourceType(executor.dataSourceType);
            returnValue = joinPoint.proceed(new SpecifiedDataSourceExecutor[]{executor});
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            DataSourceContextHolder.setDataSourceType(originalDataSourceType);
        }
        return returnValue;
    }


}