package jp.ac.osaka_u.ist.sel.similarity.csv;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import au.com.bytecode.opencsv.CSVWriter;

public class CloneCsvExporter {
    
    private CloneCsvExporter() {
    }

    /**
     * 
     * @param file
     * @param headers : header names
     * @param table : table columns (each column is map, whose key is header name).
     * @throws IOException
     */
    public static void export(File file, List<String> headers, List<Map<String,String>> table) throws IOException {
        FileWriter filewriter = null;
        CSVWriter csvwriter = null;

        try {
            filewriter = new FileWriter(file);
            csvwriter = new CSVWriter(filewriter);

            String[] colsArray = new String[headers.size()];
            int i;
            // write headers
            i = 0;
            for (String headerName : headers) {
                colsArray[i++] = headerName;
            }
            csvwriter.writeNext(colsArray);
            // write data
            for (Map<String,String> cols : table) {
                i = 0;
                for (String headerName : headers) {
                    colsArray[i++] = cols.get(headerName);
                }
                csvwriter.writeNext(colsArray);
            }
        } finally {
            if (csvwriter != null) {
                csvwriter.close();
            }
            if (filewriter != null) {
                filewriter.close();
            }
        }
    }
}
