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

import nuts.core.lang.Exceptions;
import nuts.core.log.Log;
import nuts.core.log.Logs;

import java.io.StringWriter;
import java.util.List;

import freemarker.template.Template;

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

	/**
	 * Constructor
	 * @param sqlManager sqlManager
	 */
	protected FreemarkerSqlExecutor(FreemarkerSqlManager sqlManager) {
		super(sqlManager);
	}

	/**
	 * @return the sqlManager
	 */
	public FreemarkerSqlManager getFreemarkerSqlManager() {
		return (FreemarkerSqlManager)getSqlManager();
	}

	/**
	 * parseSqlStatement
	 * @param sql sql
	 * @param parameterObject parameter object
	 * @param sqlParams sql parameter list
	 * @return translated sql
	 */
	@Override
	protected String parseSqlStatement(String sql, Object parameterObject, List<SqlParameter> sqlParams) {
		try {
			StringWriter sw = new StringWriter();
	
			Template template = getFreemarkerSqlManager().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);
			}
		}
		catch (Exception e) {
			throw Exceptions.wrapThrow(e);
		}

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