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

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.enums.TargetType;
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 data of the CSV file is done and the import is done to a remote data base
 * or a local data base. Moreover, the table data of a local data base is done
 * and the import is done to a remote data base. The data of the import object
 * targets everything.
 * 
 * @author Y.Murakamin
 * @see net.murakamin.sticker.commands.ExportCommand
 * @see net.murakamin.sticker.commands.enums.TargetType
 * 
 */
public class ImportCommand implements Command, StickerCSVDataHandler
{
	private final Log log = LogFactory.getLog(Command.class);

	private ConnectionPool conPool;
	private String destination;
	private String fileCharset = SystemUtils.FILE_ENCODING;
	private boolean header = true;
	private String labe;
	private char quote = CSVParser.QUOTE_NONE;
	private char separator = ',';
	private String source;
	private TargetType target = TargetType.remote;
	private StickerContext context;

	public ImportCommand()
	{
		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;
		if (TargetType.local == this.target)
		{
			targetConnection = this.conPool.getLocalConnection();
		} else
		{
			targetConnection = this.conPool.getRemoteConnection();
		}

		stmt = targetConnection.prepareStatement(sql);
		int parameterIndex = 1;
		for (Object field : currentDatas)
		{
			if ("".equals(field))
			{
				stmt.setNull(parameterIndex, java.sql.Types.OTHER);
			} else
			{
				stmt.setString(parameterIndex, (String) 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();
	}

	/**
	 * execute the csv data import.If the name specified with source doesn't
	 * exist as a table name of a local data base, the import does data from the
	 * CSV file. When it is not so, the import does data from the table of a
	 * local 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();
			if (!this.conPool.existsLocalTable(this.getSource()))
			{
				String source = StickerContextUtil.getReplacementString(
				        this.context, this.getSource());
				new CSVParser(this).doParse(new File(source));
			} else
			{
				Connection sourceConnection = null;
				String sourceTableName = null;

				sourceConnection = this.conPool.getLocalConnection();
				sourceTableName = StickerContextUtil.getReplacementString(
				        this.context, this.getSource());

				stmt = sourceConnection.prepareStatement("select * from "
				        + sourceTableName);

				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 table name. Local data base table name or
	 * remote data base table name
	 * 
	 * @return The import destination table name.
	 */
	public String getDestination()
	{
		return destination;
	}

	/**
	 * get the name of csv file encoding
	 * 
	 * @return the csv file encoding
	 * @see net.murakamin.csv.CSVDataHandler#getFileCharset()
	 */
	public String getFileCharset()
	{
		return fileCharset;
	}

	/**
	 * @deprecated
	 */
	@Deprecated
	public String getLabe()
	{
		return labe;
	}

	/**
	 * get the csv quote charactor. default value is '"'.
	 * 
	 * @return the csv quote charactor
	 * @see net.murakamin.csv.CSVDataHandler#getQuote()
	 */
	public char getQuote()
	{
		return quote;
	}

	/**
	 * get the csv field separator charactor. default value is ','.
	 * 
	 * @return the csv field separator charactor
	 * @see net.murakamin.csv.CSVDataHandler#getSeparator()
	 */
	public char getSeparator()
	{
		return separator;
	}

	/**
	 * An import former name of data (CSV file name or table name) is acquired.
	 * 
	 * @return An import former name of data (CSV file name or table name) is
	 *         acquired.
	 */
	public String getSource()
	{
		return source;
	}

	/**
	 * The acquisition source of the CSV data is acquired.
	 * 
	 * @return the source of data acquisition
	 */
	public String getTarget()
	{
		return this.target.name();
	}

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

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

	/**
	 * If the header is included in the CSV data that does the import, it is
	 * true.
	 * 
	 * @return If the header is included in the CSV data that does the import,
	 *         it is true.
	 */
	public boolean isHeader()
	{
		return header;
	}

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

	/**
	 * set the name of csv file encoding
	 * 
	 * @param charset
	 *            the csv file encoding
	 * @see net.murakamin.csv.CSVDataHandler#getFileCharset()
	 */
	public void setFileCharset(final String charset)
	{
		this.fileCharset = charset;
	}

	/**
	 * If the header is included in the CSV data that does the import, it is
	 * true.
	 * 
	 * @param header
	 *            If the header is included in the CSV data that does the
	 *            import, it is true.
	 */
	public void setHeader(final boolean header)
	{
		this.header = header;
	}

	/**
	 * @deprecated
	 */
	@Deprecated
	public void setLabe(final String labe)
	{
		this.labe = labe;
	}

	/**
	 * set the csv quote charactor. default value is '"'.
	 * 
	 * @param quot
	 *            the csv quote charactor
	 * @see net.murakamin.csv.CSVDataHandler#getQuote()
	 */
	public void setQuote(final char quot)
	{
		this.quote = quot;
	}

	/**
	 * set the csv field separator charactor. default value is ','.
	 * 
	 * @param separator
	 *            the csv field separator charactor
	 */
	public void setSeparator(final char separatorType)
	{
		separator = separatorType;
	}

	/**
	 * An import former name of data (CSV file name or table name) is acquired.
	 * 
	 * @param source
	 *            An import former name of data (CSV file name or table name) is
	 *            acquired.
	 * 
	 */
	public void setSource(final String source)
	{
		this.source = source;
	}

	/**
	 * The acquisition source of the CSV data is acquired.
	 * 
	 * @return the source of data acquisition
	 */
	public void setTarget(final String t)
	{
		this.target = TargetType.valueOf(t);
	}

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

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

		buffer.append(" source:");
		buffer.append(this.getSource());
		buffer.append(SystemUtils.LINE_SEPARATOR);

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

		buffer.append(" target:");
		buffer.append(this.getTarget());
		buffer.append(SystemUtils.LINE_SEPARATOR);

		buffer.append(" header:");
		buffer.append(this.isHeader());
		buffer.append(SystemUtils.LINE_SEPARATOR);

		buffer.append(" separator:");
		buffer.append(this.getSeparator());
		buffer.append(SystemUtils.LINE_SEPARATOR);

		buffer.append(" quote:");
		buffer.append(this.getQuote() == CSVParser.QUOTE_NONE ? "None" : this
		        .getQuote());
		buffer.append(SystemUtils.LINE_SEPARATOR);

		buffer.append(" charset:");
		buffer.append(this.getFileCharset());
		buffer.append(SystemUtils.LINE_SEPARATOR);

		return buffer.toString();
	}

}
