package com.rjconsultores.routing;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.rjconsultores.ventaboletos.utilerias.ApplicationProperties;

@Aspect
@Component
@Order(0)
public class ReadOnlyRouteInterceptor {
	private static final Logger log = LogManager.getLogger(ReadOnlyRouteInterceptor.class);
			
	@Around("@annotation(readOnlyConnection)")
	public Object proceed(ProceedingJoinPoint proceedingJoinPoint, ReadOnlyConnection readOnlyConnection) throws Throwable {
	    if (ApplicationProperties.getInstance().getReadOnlyConnection()) {
			try {
				String className = proceedingJoinPoint.getSignature().getDeclaringTypeName();
				String methodName = proceedingJoinPoint.getSignature().getName();

				log.debug("*** READ *** [" + className + "." + methodName + "()");
			} catch (Exception e) {}
			
			try {
				DynamicDataSourceHolder.setRouteKey("dataSourceRead");
				
				return proceedingJoinPoint.proceed();
			} finally {
				DynamicDataSourceHolder.removeRouteKey();
			}
	    } else {
			return proceedingJoinPoint.proceed();
	    }
	}
}
