package gov.va.med.edp.dao.jdbc;

import gov.va.med.edp.dao.SiteCodeLookUpDao;

import java.util.List;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.Assert;

public class JdbcSiteCodeLookUpDao implements SiteCodeLookUpDao, InitializingBean {

	private JdbcTemplate jdbcTemplate;
    private static Logger logger = Logger.getLogger(JdbcSiteCodeLookUpDao.class);
	
	
    public String getSiteCode(String machineName) throws DataAccessException {
    	String sql = "select siteCode from EDP.SiteMapper where sitePrefix=?";
    	String siteCode = "";
    	List siteCodeList = null;

    	if (logger.isDebugEnabled()){
    		logger.debug("Executing SQL: " + sql + " with parameter: " + machineName);
    	}
    	siteCodeList = jdbcTemplate.queryForList(sql, new Object[]{machineName} , String.class);
    	if (!(siteCodeList!= null && siteCodeList.size() == 1)){
    		String sitePrefix = parseSitePrefix(machineName);
    		if (logger.isDebugEnabled()){
    			logger.debug("Matching site code was not found for the full machineName. Now executing SQL query:" + sql + " with parameter: " + sitePrefix);
    		}
    		siteCodeList = jdbcTemplate.queryForList(sql, new Object[]{sitePrefix} , String.class);
    	}	  

    	if (siteCodeList!= null && siteCodeList.size() == 1){
    		siteCode = siteCodeList.get(0).toString();
    		if (logger.isDebugEnabled()) logger.debug("SQL Query executed successfully. The Site Code is: " + siteCode);
    		return siteCode;
    	} 

    	if (logger.isDebugEnabled()) logger.debug("No Results were found for the SQL Query. Returning null for siteCode");
    	return null;
    }

	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}


	public void afterPropertiesSet() throws Exception {
		Assert.notNull(jdbcTemplate, "jdbcTemplate must not be null");		
	}

	private String parseSitePrefix(String machineName){
		 String sitePrefix = "";
		 if (machineName.startsWith("VHA")){
			 sitePrefix = machineName.substring(3, 6);
			 
		 } else {
			 sitePrefix = machineName.substring(0, 3);
		 }
		
		if (logger.isDebugEnabled()){
			  logger.debug("Parsed sitePrefix from the machineName: " + machineName + " is: " + sitePrefix);
		  }		
		return sitePrefix;
	}
	
}
