package eu.dnetlib.data.collector.plugins.excel;

/**
 * Created by miriam on 10/05/2017.
 */
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVFormat;

public class CSVFileWriter {
	private static final String NEW_LINE_SEPARATOR = "\n";

	private Object [] file_header ;
	private ArrayList<ArrayList<String>> projects = new ArrayList<ArrayList<String>>();

	public void setHeader(String[] header){
		this.file_header = header;
	}

	public void addProject(ArrayList<String> project) {
		projects.add(project);

	}

	public void writeFile(String csv_file_path){
		BufferedWriter writer = null;
		CSVPrinter csvFilePrinter = null;

		CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);

		try{
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csv_file_path),"UTF-8"));

			csvFilePrinter = new CSVPrinter(writer,csvFileFormat);
			csvFilePrinter.printRecord(file_header);

			for(ArrayList<String> project:projects){
				csvFilePrinter.printRecord(project);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				writer.flush();
				writer.close();
				csvFilePrinter.close();
			}catch(IOException ioe){
				ioe.printStackTrace();
			}
		}
	}

}
