/**
 *   Copyright 2007 Y.Murakamin
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package net.murakamin.sticker.commands;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import net.murakamin.sticker.CommandRunner;
import net.murakamin.sticker.StickerContext;
import net.murakamin.sticker.commands.enums.TargetType;
import net.murakamin.sticker.commands.exception.CommandExecutionException;
import net.murakamin.sticker.commands.util.StickerContextUtil;

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

public class SqlCommand implements Command
{

	private final Log log = LogFactory.getLog(Command.class);
	private String sql;
	private TargetType target = TargetType.remote;
	private boolean ignore = false;

	public void execute(final CommandRunner runner) throws Exception
	{
		PreparedStatement stmt = null;
		try
		{
			Connection targetConnection = runner.getConnectionPool()
			        .getRemoteConnection();
			if (TargetType.local == this.target)
			{
				targetConnection = runner.getConnectionPool()
				        .getLocalConnection();
			}

			StickerContext context = runner.getStickerContext();
			String sqlStatement = StickerContextUtil.applyContextVariable(
			        context, this.getSql());
			sqlStatement = StickerContextUtil.getReplacementString(context,
			        sqlStatement);
			sqlStatement = sqlStatement.replaceAll("\t", " ");

			if (StringUtils.trim(this.getSql()).matches(
			        "(?i)(^\\?\\s*=\\s*call.*)|(^call.*)"))
			{
				// if callable statement(stored procedure)
				stmt = targetConnection.prepareCall("{" + sqlStatement + "}");
			} else
			{
				// sql statement
				stmt = targetConnection.prepareStatement(sqlStatement);
			}
			stmt.execute();
			runner.run(this);
		} catch (SQLException e)
		{
			if (this.isIgnore() == false)
			{
				throw new CommandExecutionException(this, e);
			}
			this.log.warn("SQL発行でエラーが発生しましたが、ignore=trueが指定されているので無視しました。"
			        + e.getMessage());
		} finally
		{
			if (stmt != null)
			{
				stmt.close();
			}
		}
	}

	public String getSql()
	{
		return this.sql;
	}

	public String getTarget()
	{
		return this.target.name();
	}

	public VersionTerm getVersionTerm()
	{
		return VersionTerm.PERMANENT_COMMAND;
	}

	public boolean isDebugPrint()
	{
		return true;
	}

	public boolean isIgnore()
	{
		return ignore;
	}

	public void setIgnore(final boolean ignore)
	{
		this.ignore = ignore;
	}

	public void setSql(final String statement)
	{
		this.sql = statement;
	}

	public void setTarget(final String value)
	{
		this.target = TargetType.valueOf(value);
	}

	@Override
	public String toString()
	{
		return this.getSql();
	}
}
