/*
 * 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.core.orm.sql.engine;

import java.io.StringWriter;
import java.net.URL;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import nuts.core.lang.ClassLoaderUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.cache.URLTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * FreemarkerSqlExecutor.
 */
public class FreemarkerSqlExecutor extends SimpleSqlExecutor {
	/**
	 * log
	 */
	private static Log log = LogFactory.getLog(FreemarkerSqlExecutor.class);

	/**
	 * configuration
	 */
	private static Configuration configuration;

	/**
	 * ClassTemplateLoader
	 */
	public static class ClassTemplateLoader extends URLTemplateLoader {
		protected URL getURL(String name) {
			return ClassLoaderUtils.getResourceAsURL(name, getClass());
		}
	}
	
	/**
	 * @return the configuration
	 * @throws Exception if an error occurs
	 */
	public static Configuration getConfiguration() throws Exception {
		if (configuration == null) {
			configuration = new Configuration();

			List<TemplateLoader> tls = new ArrayList<TemplateLoader>();
			tls.add(new ClassTemplateLoader());
			tls.add(new FileTemplateLoader());
			
			MultiTemplateLoader mtl = new MultiTemplateLoader(tls.toArray(new TemplateLoader[tls.size()]));
			
			configuration.setTemplateLoader(mtl);
		}
		return configuration;
	}

	/**
	 * @param configuration the configuration to set
	 */
	public static void setConfiguration(Configuration configuration) {
		FreemarkerSqlExecutor.configuration = configuration;
	}

	/**
	 * Constructor
	 * 
	 * @param connection connection
	 */
	public FreemarkerSqlExecutor(Connection connection) {
		super(connection);
	}

	/**
	 * Constructor
	 * 
	 * @param connection connection
	 * @param resultSetType one of the following ResultSet constants: ResultSet.TYPE_FORWARD_ONLY,
	 *            ResultSet.TYPE_SCROLL_INSENSITIVE, or ResultSet.TYPE_SCROLL_SENSITIVE
	 */
	public FreemarkerSqlExecutor(Connection connection, int resultSetType) {
		super(connection, resultSetType);
	}

	/**
	 * Constructor
	 * 
	 * @param connection connection
	 * @param resultSetType one of the following ResultSet constants: ResultSet.TYPE_FORWARD_ONLY,
	 *            ResultSet.TYPE_SCROLL_INSENSITIVE, or ResultSet.TYPE_SCROLL_SENSITIVE
	 * @param resultSetConcurrency one of the following ResultSet constants:
	 *            ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE
	 */
	public FreemarkerSqlExecutor(Connection connection, int resultSetType, int resultSetConcurrency) {
		super(connection, resultSetType, resultSetConcurrency);
	}

	/**
	 * Constructor
	 * 
	 * @param connection connection
	 * @param resultSetType one of the following ResultSet constants: ResultSet.TYPE_FORWARD_ONLY,
	 *            ResultSet.TYPE_SCROLL_INSENSITIVE, or ResultSet.TYPE_SCROLL_SENSITIVE
	 * @param resultSetConcurrency one of the following ResultSet constants:
	 *            ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE
	 * @param resultSetHoldability one of the following ResultSet constants:
	 *            ResultSet.HOLD_CURSORS_OVER_COMMIT or ResultSet.CLOSE_CURSORS_AT_COMMIT
	 */
	public FreemarkerSqlExecutor(Connection connection, int resultSetType, int resultSetConcurrency,
			int resultSetHoldability) {
		super(connection, resultSetType, resultSetConcurrency, resultSetHoldability);
	}

	/**
	 * parseSqlStatement
	 * @param sql sql
	 * @param parameterObject parameter object
	 * @param sqlParams sql parameter list
	 * @return translated sql
	 * @throws Exception if an error occurs
	 */
	@Override
	protected String parseSqlStatement(String sql, Object parameterObject,
			List<SqlParameter> sqlParams) throws Exception {

		StringWriter sw = new StringWriter();

		Template template = getConfiguration().getTemplate(sql);
		if (template == null) {
			throw new IllegalArgumentException("Failed to load SQL template: " + sql);
		}
		template.process(parameterObject, sw);
		
		sql = sw.toString();
		if (log.isDebugEnabled()) {
			log.debug(sql);
		}

		return super.parseSqlStatement(sql, parameterObject, sqlParams);
	}
}
