package gov.va.med.ars.audit;

import gov.va.med.ars.beans.AuditLog;
import gov.va.med.ars.spring.dao.DbLogManagerDao;
import gov.va.med.ars.spring.dao.DbLogManagerDaoImpl;

import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jndi.JndiTemplate;
import org.springframework.stereotype.Component;

@Component
public class AuditLogger  {
	
	@Autowired
	private DbLogManagerDao dbLogManagerDao;
	static final Logger errorLogger = Logger.getLogger("errorLogger");
	static final Logger auditLogger = Logger.getLogger("auditLogger");
	
	public void doAuditing(AuditLog auditLog)
	{
		try
		{
			dbLogManagerDao = getDbLogManagerDao();
			
			if( dbLogManagerDao == null)
			{
				auditLogger.info("dbLogManagerDao is null");
			}
			else if ( auditLog == null )
			{
				auditLogger.info("auditLog is null");
			}
			
			dbLogManagerDao.logOperation(auditLog);
		}
		catch ( Exception e)
		{
			e.printStackTrace();
			logAuditToFile(auditLog);
		}
	}
	
	public DbLogManagerDao getDbLogManagerDao() throws NamingException {
		JndiTemplate jndiTemplate = new JndiTemplate();
		DataSource dataSource = (DataSource) jndiTemplate.lookup("java:comp/env/jdbc/ArsDB");
		//return new DbLogManagerDaoImpl(getDataSource());
		return new DbLogManagerDaoImpl(dataSource);
	}
	
	
	
	/**
	 * logs to the configured logger in a csv format for easier viewing and manipulation
	 * 
	 * @param auditLog
	 */
	private void logAuditToFile(AuditLog auditLog)
	{
		char separator = ',';
		
		StringBuilder s = new StringBuilder();
		
		s.append(""+auditLog.getMethodName()+separator);
		s.append(""+auditLog.getUserId()+separator);
		s.append(""+auditLog.getClaimAttachmentId()+separator);
		//s.append(""+auditLog.getLocalDateTime()+separator);
		s.append(""+auditLog.getAction()+separator);
		s.append(""+auditLog.getSuccess()+separator);
		s.append(""+auditLog.getAccessDate()+separator);
		s.append(""+auditLog.getVer()+separator);
		s.append(""+auditLog.getRequestArgs()+separator);
		
		String auditLine = s.toString();
		auditLogger.info(auditLine);
		
	}

}
