/**
 *   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.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import net.murakamin.csv.CSVDataHandler;
import net.murakamin.csv.CSVParser;
import net.murakamin.sticker.CommandRunner;
import net.murakamin.sticker.ConnectionPool;
import net.murakamin.sticker.Sticker;
import net.murakamin.sticker.StickerContext;
import net.murakamin.sticker.commands.exception.CommandExecutionException;
import net.murakamin.sticker.commands.util.StickerContextUtil;

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

/**
 * The import does data from a local data base to a remote data base. Data
 * ..import.. can be decided according to the Select statement.
 * 
 * @author Y.Murakamin
 * @see net.murakamin.sticker.commands.ExportCommand
 * @see net.murakamin.sticker.commands.enums.TargetType
 * 
 */
public class QueryImportCommand implements Command, CSVDataHandler
{
	private final Log log = LogFactory.getLog(Command.class);

	private ConnectionPool conPool;
	private String destination;
	private String sql;

	private StickerContext context;

	public QueryImportCommand()
	{
		super();
	}

	/**
	 * The import does one line's worth of of CSV data or record data.
	 * 
	 * @see net.murakamin.csv.CSVDataHandler#addCSVData(String[])
	 */
	public void addCSVData(final String[] currentDatas) throws Exception
	{

		String destination = StickerContextUtil.getReplacementString(
		        this.context, this.getDestination());
		String sql = this.createInsertPrepareStatement(destination,
		        currentDatas);

		PreparedStatement stmt = null;

		Connection targetConnection = null;
		targetConnection = this.conPool.getRemoteConnection();

		stmt = targetConnection.prepareStatement(sql);
		int parameterIndex = 1;
		for (Object field : currentDatas)
		{
			stmt.setObject(parameterIndex, field);
			parameterIndex++;
		}

		if (Sticker.isDebug())
		{
			StringBuffer buffer = new StringBuffer();
			for (String param : currentDatas)
			{
				buffer.append('[');
				buffer.append(param);
				buffer.append(']');
			}
			this.log.debug(stmt + ": parameters=" + buffer.toString());
		}
		try
		{
			stmt.executeUpdate();
		} catch (Exception e)
		{
			StringBuffer buffer = new StringBuffer();
			for (String param : currentDatas)
			{
				buffer.append('[');
				buffer.append(param);
				buffer.append(']');
			}

			this.log.error(buffer.toString());
			throw e;
		} finally
		{
			if (stmt != null)
			{
				stmt.close();
			}
		}
	}

	/**
	 * 
	 * To store one line's worth of of CSV data or record data in the data base,
	 * the INSERT statement is generated.
	 * 
	 * @param targetTable
	 *            table name
	 * @param values
	 *            insert values
	 * @return insert statement(SQL statement)
	 * @throws UnsupportedEncodingException
	 */
	private String createInsertPrepareStatement(final String targetTable,
	        final String[] values) throws UnsupportedEncodingException
	{
		StringBuffer sql = new StringBuffer("insert into ");

		sql.append(targetTable);
		sql.append(" values (");
		for (String field : values)
		{
			sql.append('?');
			sql.append(',');
		}
		sql.replace(sql.length() - 1, sql.length(), ")");

		return sql.toString();
	}

	/**
	 * The import does data from a local data base to a remote data base.
	 * 
	 * @see net.murakamin.sticker.commands.execute(CommandRunner runner)
	 */
	public void execute(final CommandRunner runner) throws Exception
	{

		PreparedStatement stmt = null;
		ResultSet rs = null;
		this.context = runner.getStickerContext();
		try
		{
			this.conPool = runner.getConnectionPool();

			Connection sourceConnection = this.conPool.getLocalConnection();

			String sql = StickerContextUtil.applyContextVariable(this.context,
			        this.getSql());
			String executableSql = StickerContextUtil.getReplacementString(
			        this.context, sql);
			stmt = sourceConnection.prepareStatement(executableSql);

			rs = stmt.executeQuery();
			new CSVParser(this).doParse(rs);
			runner.run(this);
		} catch (Exception e)
		{
			throw new CommandExecutionException(this, e);
		} finally
		{
			if (rs != null)
			{
				rs.close();
			}
			if (stmt != null)
			{
				stmt.close();
			}
		}
	}

	/**
	 * get the import destination remote database table name.
	 * 
	 * @return The import destination table name.
	 */
	public String getDestination()
	{
		return destination;
	}

	/**
	 * always exception throwing
	 * 
	 * @throws UnsupportedOperationException
	 * @see net.murakamin.csv.CSVDataHandler#getFileCharset()
	 */
	public String getFileCharset()
	{
		throw new UnsupportedOperationException();
	}

	/**
	 * always exception throwing
	 * 
	 * @throws UnsupportedOperationException
	 * @see net.murakamin.csv.CSVDataHandler#getQuote()
	 */
	public char getQuote()
	{
		throw new UnsupportedOperationException();
	}

	/**
	 * always exception throwing
	 * 
	 * @throws UnsupportedOperationException
	 * @see net.murakamin.csv.CSVDataHandler#getSeparator()
	 */
	public char getSeparator()
	{
		throw new UnsupportedOperationException();
	}

	/**
	 * always exception throwing
	 * 
	 * @throws UnsupportedOperationException
	 */
	public String getSource()
	{
		throw new UnsupportedOperationException();
	}

	/**
	 * get the sql statement.
	 * 
	 * @return It is SQL statement to extract it as for data ..import...
	 * 
	 */
	public String getSql()
	{
		return sql;
	}

	/**
	 * always exception throwing
	 * 
	 * @throws UnsupportedOperationException
	 */
	public String getTarget()
	{
		throw new UnsupportedOperationException();
	}

	/**
	 * @see net.murakamin.sticker.commands.ExecutableCommand#getVersionTerm()
	 */
	public VersionTerm getVersionTerm()
	{
		return new VersionTerm("0.0.7");
	}

	/**
	 * @see net.murakamin.sticker.commands.ExecutableCommand#isDebugPrint()
	 */
	public boolean isDebugPrint()
	{
		return true;
	}

	/**
	 * always exception throwing
	 * 
	 * @throws UnsupportedOperationException
	 */
	public boolean isHeader()
	{
		throw new UnsupportedOperationException();
	}

	/**
	 * set the import destination remote database table name.
	 * 
	 * @param dest
	 *            The import destination table name.
	 */
	public void setDestination(final String dest)
	{
		this.destination = dest;
	}

	/**
	 * always exception throwing
	 * 
	 * @throws UnsupportedOperationException
	 */
	public void setFileCharset(final String charset)
	{
		throw new UnsupportedOperationException();
	}

	/**
	 * always exception throwing
	 * 
	 * @throws UnsupportedOperationException
	 */
	public void setHeader(final boolean header)
	{
		throw new UnsupportedOperationException();
	}

	/**
	 * always exception throwing
	 * 
	 * @throws UnsupportedOperationException
	 */
	public void setQuote(final char quot)
	{
		throw new UnsupportedOperationException();
	}

	/**
	 * always exception throwing
	 * 
	 * @throws UnsupportedOperationException
	 */
	public void setSeparator(final char separatorType)
	{
		throw new UnsupportedOperationException();
	}

	/**
	 * always exception throwing
	 * 
	 * @throws UnsupportedOperationException
	 */
	public void setSource(final String source)
	{
		throw new UnsupportedOperationException();
	}

	/**
	 * set the sql statement.
	 * 
	 * @param sql
	 *            It is SQL statement to extract it as for data ..import...
	 * 
	 */
	public void setSql(final String sql)
	{
		this.sql = sql;
	}

	/**
	 * always exception throwing
	 * 
	 * @throws UnsupportedOperationException
	 */
	public void setTarget(final String t)
	{
		throw new UnsupportedOperationException();
	}

	@Override
	public String toString()
	{
		StringBuffer buffer = new StringBuffer();

		buffer.append("<queryImport> query import execute:");
		buffer.append(SystemUtils.LINE_SEPARATOR);

		buffer.append(" destination:");
		buffer.append(this.getDestination());
		buffer.append(SystemUtils.LINE_SEPARATOR);

		buffer.append(" query:");
		buffer.append(this.getSql());
		buffer.append(SystemUtils.LINE_SEPARATOR);

		return buffer.toString();
	}

}
