package nuts.exts.app;

import java.util.Properties;

import nuts.core.orm.dao.DataAccessClient;
import nuts.exts.mybatis.MyBatisDataAccessClient;
import nuts.exts.mybatis.MyBatisDataAccessClientFactory;

public class MyBatisHelper {
	private static final String SQL_MAP_CONFIG = "mybatis-sqlmap-config.xml";

	public static DataAccessClient buildDataAccessClient() throws Exception {
		Properties properties = WebApplication.getProperties();
		
		WebApplication.log.info("Building dataAccessClient ...");

		String jdbcUrl = properties.getProperty("jdbc.url");
		if (jdbcUrl != null) {
			if (jdbcUrl.startsWith("jdbc:hsqldb:file:")) {
				int i = jdbcUrl.indexOf("/WEB-INF/");
				if (i > 0) {
					jdbcUrl = "jdbc:hsqldb:file:" 
						+ WebApplication.getServletContext().getRealPath(jdbcUrl.substring(i));
					properties.setProperty("jdbc.url", jdbcUrl);
				}
			}
		}
		
		String dstype = properties.getProperty("datasource.type");
		if ("NSIMPLE".equalsIgnoreCase(dstype)) {
			WebApplication.log.debug("jdbc - " + properties.getProperty("jdbc.driver") + ":" + properties.getProperty("jdbc.url"));
		}
		else if ("JNDI".equalsIgnoreCase(dstype)) {
			WebApplication.log.debug("jndi.resource - " + properties.getProperty("jndi.resource"));
		}
		else {
			throw new IllegalArgumentException("The data source type [" + dstype + "] is invalid.");
		}

		MyBatisDataAccessClient dac = MyBatisDataAccessClientFactory.buildDataAccessClient(SQL_MAP_CONFIG, properties);
		
		return dac;
	}
}
