/*
 * This file is part of Nuts Framework.
 * Copyright (C) 2009 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.exts.mybatis;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import nuts.core.io.IOUtils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


/**
 */
public class MyBatisDataAccessClientFactory {

	private static Map<String, MyBatisDataAccessClient> dataAccessClients = new HashMap<String, MyBatisDataAccessClient>();

	/**
	 * build dataAccessClient object
	 * 
	 * @param name  the sql-map-config.xml configuration file resource name.
	 * @return DataAccessClient instance.
	 */
	public static MyBatisDataAccessClient buildDataAccessClient(String name) {
		return buildDataAccessClient(name, null);
	}
	
	/**
	 * build dataAccessClient object
	 * 
	 * @param name  the sql-map-config.xml configuration file resource name.
	 * @param props properties to be used to provide values to dynamic property tokens in the
	 *            sql-map-config.xml configuration file. This provides an easy way to achieve some
	 *            level of programmatic configuration.
	 * @return DataAccessClient instance.
	 */
	public static MyBatisDataAccessClient buildDataAccessClient(String name, Properties props) {
		InputStream is = null;
		try {
			is = Resources.getResourceAsStream(name);
			MyBatisDataAccessClient dac = new MyBatisDataAccessClient(new SqlSessionFactoryBuilder().build(is, props), props);
			dac.setName(name);
			dataAccessClients.put(name, dac);
			return dac;
		}
		catch (IOException e) {
			throw new RuntimeException("Can not load " + name, e);
		}
		finally {
			IOUtils.closeQuietly(is);
		}
	}

	/**
	 * getDataAccessClient
	 * @param name  the sql-map-config.xml configuration file resource name.
	 * @return DataAccessClient instance.
	 */
	public static MyBatisDataAccessClient getDataAccessClient(String name) {
		MyBatisDataAccessClient smc = dataAccessClients.get(name);
		if (smc == null) {
			return buildDataAccessClient(name);
		}
		return smc;
	}
}
