/*
 *
 * Copyright (C) 09-sept.-2003  Jean-Yves Beaujean 
 * This program 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 2 of the License, or (at your option)
 * any later version.
 * This program 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
 * this program; if not, write to the Free Software Foundation, Inc.,  59
 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 * 
 */
package jxtray.dump;


import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
import java.sql.Connection;
import java.sql.Types;

import jxtray.Jxtray;

import jxtray.util.TimeUtilities;

import jxtray.io.*;


/** This class dump data in CSV  format.
 *  No structure dump in this format. Dump datas only.
 */
public class JxtCSVDumpStrategy extends JxtDumpStrategy implements Runnable 
{

	
	public JxtCSVDumpStrategy(String filename,DumperListener listener,Connection connection,String lib, String table, WriterContext writer)
	{
		super(filename,listener,connection,lib,table,writer);
	}
	
	public void run()
	{
		_finished=false;
		try
		{
			double t = System.currentTimeMillis();
			dumpStructure();
			dumpData();
			double diff = System.currentTimeMillis()-t;
			_listener.dumpLog("\n"+Jxtray.getLang("dump.operation_time")+ TimeUtilities.smartTime(diff/1000) );
			_output.close();
		}
		catch ( Exception e )
		{
			_listener.dumpError(e.getMessage());
		}
		catch ( Error e )
		{
			_listener.dumpError(e.getMessage());
		}		
		_listener.dumpEnded();
		_finished=true;
		_thread=null;
	}
	
	public String getName() 
	{ 
		return "CSV Dumper";
	}
	
	protected void dumpData()
	{
		StringBuffer query = new StringBuffer();
		try
		{
			if ( _connection.getMetaData().supportsCatalogsInDataManipulation() || _connection.getMetaData().supportsSchemasInDataManipulation() )
				query.append("select * from ").append(_lib).append(".").append(_table);
			else
				query.append("select * from ").append(_table);		

			_listener.dumpLog("\n"+Jxtray.getLang("dump.execute_query")+query);
			_listener.dumpState(Jxtray.getLang("dump.select_datas"));
			Statement stmt =  _connection.createStatement();
			ResultSet res = stmt.executeQuery(query.toString());
			ResultSetMetaData rmtd =  res.getMetaData();
			_listener.dumpLog("\n"+Jxtray.getLang("dump.tablefields"));
			_listener.dumpState(Jxtray.getLang("dump.structure"));
			for ( int i=0; i< rmtd.getColumnCount();i++)
			{
				if ( i > 0 )
					_output.write(Jxtray.getProperty("csv.separator"));
				_listener.dumpLog("\n"+rmtd.getColumnName(i+1));
				_output.write(rmtd.getColumnName(i+1));
			}
			_output.write("\n");
			int ctype =-1;
			String fieldValue;
			StringBuffer record = null;
			while ( res.next())
			{
					_cpt++; 
					_listener.dumpNextRecord(_cpt);
					record = new StringBuffer();
					for ( int i = 0 ; i < rmtd.getColumnCount();i++)
					{
						ctype = rmtd.getColumnType(i+1);
						fieldValue =res.getString(i+1);
						if ( i > 0 )
							record.append(Jxtray.getProperty("csv.separator"));
								
						if ( ctype == Types.CHAR || ctype == Types.LONGVARCHAR || ctype == Types.VARCHAR)
							record.append(Jxtray.getProperty("csv.textdelimitor")).append(fieldValue).append(Jxtray.getProperty("csv.textdelimitor"));
						else
						{
							if ( fieldValue == null)
								record.append("null");
							else
								record.append(fieldValue);
						}
					}
					record.append("\n");
					_output.write(record.toString());
					
			}
			res.close();
			stmt.close();
		}
		catch ( Exception e )
		{
			_listener.dumpError(e.getMessage());
		}
		
		catch ( Error e )
		{
			_listener.dumpError(e.getMessage());
		}
		
		_listener.dumpLog("\n"+_cpt+Jxtray.getLang("dump.recordsdumped"));
	}
	
	protected void dumpStructure()
	{
		// no dump structure with CSV Format.
	}		
}
