/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.aems;

import nuts.core.dao.DaoClient;
import nuts.exts.mybatis.MyBatisDataAccessClient;
import nuts.exts.mybatis.MyBatisDataAccessClientFactory;

import java.util.Properties;

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

	public static DaoClient buildDataAccessClient() throws Exception {
		Properties properties = WebApplet.get().getProperties();
		
		WebApplet.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:" 
						+ WebApplet.get().getServletContext().getRealPath(jdbcUrl.substring(i));
					properties.setProperty("jdbc.url", jdbcUrl);
				}
			}
		}
		
		String dstype = properties.getProperty("data.source");
		if ("NSIMPLE".equalsIgnoreCase(dstype)) {
			WebApplet.log.debug("jdbc - " + properties.getProperty("jdbc.driver") + ":" + properties.getProperty("jdbc.url"));
		}
		else if ("JNDI".equalsIgnoreCase(dstype)) {
			WebApplet.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;
	}
}
