package gov.va.med.ars.spring.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

import gov.va.med.ars.beans.AuditLog;
import gov.va.med.ars.exceptions.ArsDataAccessException;
//import gov.va.kiosk.vss.services.exceptions.VSSDataAccessException;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

public class DbLogManagerDaoImpl extends BaseDao implements DbLogManagerDao 
{
	private JdbcTemplate jdbcTemplate;


	public DbLogManagerDaoImpl(DataSource dataSource) {
		jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public Integer logOperation(final AuditLog auditLog)
	{
		Integer primaryKeyId = 0;
				
		try {
			StringBuilder sb = new StringBuilder();
			sb.append("INSERT INTO [dbo].[ArsAuditLog] (");
			sb.append("MethodName");
			sb.append(",UserId");
			sb.append(",ClaimAttachmentId");//] [varchar](50) NOT NULL,
			sb.append(",AccessDate");//] [varchar] (20) NULL,
			sb.append(",RequestArgs");//] [varchar] (200) NOT NULL,
			sb.append(",Success");//] [bit] null,
			sb.append(",Action ) ");//] [varchar] (60) NULL,
			
			sb.append("values (?, ?, ?, ?, ?, ?, ?)");
			
			final String insertSQL = sb.toString();
			
			KeyHolder keyHolder = new GeneratedKeyHolder();
			
			jdbcTemplate.update(
				    new PreparedStatementCreator() {
				        public PreparedStatement createPreparedStatement(Connection connection) 
				        throws SQLException {
				        	connection  = jdbcTemplate.getDataSource().getConnection();
				            PreparedStatement ps =
				                connection.prepareStatement(insertSQL, new String[] {"id"});
				            ps.setString(1, auditLog.getMethodName());
				            ps.setString(2, auditLog.getUserId());
				            ps.setInt(3, auditLog.getClaimAttachmentId());
				            ps.setTimestamp(4, auditLog.getAccessDate());
				            ps.setString(5,auditLog.getRequestArgs());
				            ps.setBoolean(6,true);
				            ps.setString(7, auditLog.getAction());
			            
				            return ps;
				        }
				    },
				    keyHolder);
			
			
			primaryKeyId = keyHolder.getKey().intValue();


		} catch (DataAccessException e) {

			e.printStackTrace();
			throw new ArsDataAccessException(e.getMessage(),e);
			
		} 

		return primaryKeyId;

	}
	
}
