package eu.dnetlib.organizations.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opencsv.CSVWriter;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvException;

public class CSVConverter {

	private static final Log log = LogFactory.getLog(CSVConverter.class);

	public static <T> void writeCSV(final OutputStream out, final Iterable<T> list, final Class<T> clazz, final String... columns) {
		final StringWriter sw = new StringWriter();

		sw.write(StringUtils.join(columns, ","));
		sw.write(CSVWriter.DEFAULT_LINE_END);

		try {
			final ColumnPositionMappingStrategy<T> mapStrategy = new ColumnPositionMappingStrategy<>();
			mapStrategy.setType(clazz);
			mapStrategy.setColumnMapping(columns);

			final StatefulBeanToCsv<T> btcsv = new StatefulBeanToCsvBuilder<T>(sw)
				.withQuotechar(CSVWriter.DEFAULT_QUOTE_CHARACTER)
				.withEscapechar(CSVWriter.DEFAULT_ESCAPE_CHARACTER)
				.withMappingStrategy(mapStrategy)
				.withSeparator(',')
				.build();

			btcsv.write(list.iterator());

			IOUtils.write(sw.toString(), out);

		} catch (final CsvException | IOException ex) {
			log.error("Error mapping Bean to CSV", ex);
		}
	}

}
