package com.ejie.ad74a.annotation;

import java.util.Arrays;

import org.apache.poi.ss.formula.functions.T;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;

import com.ejie.ad74a.util.constantes.ConstantesSQL;

@Aspect
public class HistoricoAOP {

	private static final Logger logger = LoggerFactory.getLogger(HistoricoAOP.class);

	public static final String[] WHITE_LIST_FROM = new String[] { "EXPEDIENTES", "SOLICITANTES" };

	@Around("@annotation(HistoricoAnnotation)")
	public Object previaInvocacion(ProceedingJoinPoint joinpoint) throws Throwable {
		HistoricoAOP.logger.info("HistoricoAOP.previaInvocacion");

		boolean isHistorico = false;
		RowMapper<T> rowMapper = null;
		Object[] array = null;
		String sql = "";
		for (Object arg : joinpoint.getArgs()) {
			if (arg instanceof Boolean) {
				isHistorico = (boolean) arg;
			} else if (arg instanceof String) {
				sql = (String) arg;
			} else if (arg instanceof RowMapper) {
				rowMapper = (RowMapper<T>) arg;
			} else if (arg instanceof Object[]) {
				array = (Object[]) arg;
			}
		}
		if (isHistorico) {
			sql = makelHistoricSentence(sql);
			return joinpoint.proceed(new Object[] { sql, rowMapper, array, isHistorico });
		}

		return joinpoint.proceed();
	}

	private String makelHistoricSentence(String sql) {

		String newFrom = "";
		String sqlFinal = "";

		int desde = sql.indexOf(ConstantesSQL.FROM);
		int hasta = sql.indexOf(ConstantesSQL.WHERE);

		sqlFinal = sql.substring(0, desde);

		newFrom = sql.substring(desde + ConstantesSQL.FROM.length(), hasta);

		String[] tablas = newFrom.split(",");
		for (String tab : tablas) {
			tab = tab.trim();
			int t = tab.indexOf(" ");
			tab = tab.substring(0, t);
			System.out.println(tab);
			if (Arrays.asList(WHITE_LIST_FROM).contains(tab)) {
				newFrom = newFrom.replaceAll(tab, tab + ConstantesSQL.SUFIJO_HISTORICO);
			}
		}

		sqlFinal += " " + ConstantesSQL.FROM + newFrom + sql.substring(hasta, sql.length());

		return sqlFinal;
	}

}
