/*
 * Copyright 2015 Vyacheslav Pushkin (https://github.com/singularityfx)
 * 
 * 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 org.supercsv.io;

import java.io.IOException;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.prefs.CsvPreference;
import org.supercsv.util.Util;

/**
 * CsvResultSetWriter writes a CSV file by mapping each column of the {@code ResultSet}
 * to a column in CSV file using the column names stored in {@code ResultSetMetaData}
 * 
 * @author SingularityFX
 *
 */
public class CsvResultSetWriter extends AbstractCsvWriter implements ICsvResultSetWriter {
	
	/**
	 * Constructs a new {@code CsvResultSetWriter} with the supplied {@code Writer}
	 * and CSV preferences. Note that the {@code writer} will be wrapped in a 
	 * {@code BufferedWriter} before accessed.
	 * 
	 * @param 	writer
	 * 				the writer
	 * @param 	preference
	 * 				the CSV preferences
	 * @throws 	NullPointerException
	 *          	if writer or preference are null
	 */
	public CsvResultSetWriter(Writer writer, CsvPreference preference) {
		super(writer, preference);
	}
	
	/**
	 * {@inheritDoc}
	 * 
	 */
	public void write(ResultSet resultSet) throws SQLException, IOException {
		CellProcessor[] dummyProcessors = getDummyProcessors(resultSet);
		write(resultSet, dummyProcessors);
	}
	
	// Creates an array of dummy processors which perform no processing
	private CellProcessor[] getDummyProcessors(ResultSet resultSet) throws SQLException {
		int numberOfColumns = resultSet.getMetaData().getColumnCount();
		CellProcessor[] dummyProcessors = new CellProcessor[numberOfColumns];
		for (int i = 0; i < dummyProcessors.length; i++) {
			dummyProcessors[i] = new Optional();
		}
		return dummyProcessors;
	}

	/**
	 * {@inheritDoc}
	 * 
	 */
	public void write(ResultSet resultSet, CellProcessor[] writeProcessors) throws SQLException, IOException {
		if (resultSet == null) {
			throw new NullPointerException("ResultSet cannot be null");
		}
		if (writeProcessors == null) {
			throw new NullPointerException("CellProcessor[] cannot be null");
		}
		
		writeHeaders(resultSet); // increments row and line number
		writeContents(resultSet, writeProcessors); // increments row and line number before writing of each row
	}

	private void writeHeaders(ResultSet resultSet) throws SQLException, IOException {
		super.incrementRowAndLineNo(); // This will allow the correct row/line numbers to be used in any exceptions thrown before writing occurs
		
		ResultSetMetaData meta = resultSet.getMetaData();
		final int numberOfColumns = meta.getColumnCount();
		List<Object> headers = new LinkedList<Object>();
		for (int columnIndex = 1; columnIndex <= numberOfColumns; columnIndex++) {
			headers.add(meta.getColumnName(columnIndex));
		}
		super.writeRow(headers);
	}
	
	private void writeContents(ResultSet resultSet, CellProcessor[] writeProcessors) throws SQLException, IOException {
		final int numberOfColumns = resultSet.getMetaData().getColumnCount();
		List<Object> objects = new LinkedList<Object>();
		List<Object> processedColumns = new LinkedList<Object>();
		while (resultSet.next()) {
			super.incrementRowAndLineNo(); // This will allow the correct row/line numbers to be used in any exceptions thrown before writing occurs
			objects.clear();
			for (int columnIndex = 1; columnIndex <= numberOfColumns; columnIndex++) {
				objects.add(resultSet.getObject(columnIndex));
			}
			Util.executeCellProcessors(processedColumns, objects, writeProcessors, getLineNumber(), getRowNumber());
			super.writeRow(processedColumns);
		}
	}
}

@@ -860,52 +860,8 @@
 t;%0A%0A
-import org.supercsv.cellprocessor.Optional;%0A
 impo
@@ -1893,237 +1893,127 @@
 %7B%0A%09%09
-CellProcessor%5B%5D dummyProcessors = getDummyProcessors(resultSet);%0A%09%09write(resultSet, dummyProcessors
+if (resultSet == null) %7B%0A%09%09%09throw new NullPointerException(%22ResultSet cannot be null%22
 );%0A
+%09
 %09%7D%0A%09
+%09
 %0A%09
-// Creates an array of dummy processors which perform no processing%0A%09private CellProcessor%5B%5D getDummyProcessors(R
+%09writeHeaders(r
 esultSet
  res
@@ -2012,306 +2012,138 @@
 tSet
- resultSet) throws SQLException %7B%0A%09%09int
+); // increments row and line
  number
-OfColumns = resultSet.getMetaData().getColumnCount();%0A%09%09CellProcessor%5B%5D dummyProcessors = new CellProcessor%5BnumberOfColumns%5D;%0A%09%09for (int i = 0; i %3C dummyProcessors.length; i++) %7B%0A%09%09%09dummyProcessors%5Bi%5D = new Optional();%0A%09%09%7D%0A%09%09return dummyProcessors;
+%0A%09%09writeContents(resultSet); // increments row and line number before writing of each row
 %0A%09%7D%0A
+%09
 %0A%09/*
@@ -3197,16 +3197,583 @@
 );%0A%09%7D%0A%09%0A
+%09private void writeContents(ResultSet resultSet) throws SQLException, IOException %7B%0A%09%09final int numberOfColumns = resultSet.getMetaData().getColumnCount();%0A%09%09List%3CObject%3E objects = new LinkedList%3CObject%3E();%0A%09%09while (resultSet.next()) %7B%0A%09%09%09super.incrementRowAndLineNo(); // This will allow the correct row/line numbers to be used in any exceptions thrown before writing occurs%0A%09%09%09objects.clear();%0A%09%09%09for (int columnIndex = 1; columnIndex %3C= numberOfColumns; columnIndex++) %7B%0A%09%09%09%09objects.add(resultSet.getObject(columnIndex));%0A%09%09%09%7D%0A%09%09%09super.writeRow(objects);%0A%09%09%7D%0A%09%7D%0A%09%0A
 %09private

Improve performance of CsvResultSetWriter