package org.mbari.vdm;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;

import org.mbari.vdm.expd.ExpdLine;


public class CsvHelper {
    @SuppressWarnings("unchecked")
    public static final VdmLine[] readLines(BufferedReader input, String vdmLineClass) throws IOException {
        ArrayList list = new ArrayList();
        String line;
        String[] parts;
        // skip the header line
        input.readLine();
//        System.out.println("reading data into arraylist");
        while ((line = input.readLine()) != null) {
            list.add(VdmLineFactory.makeNewVdmLine(vdmLineClass, line));
        }
        input.close();
        input = null;
        System.out.println("Read in " + list.size() + " lines");
//        System.out.println("moving data to array");
        VdmLine[] vdmLines = new VdmLine[0];
        vdmLines = (VdmLine[]) list.toArray(vdmLines);
        list.clear();
        list = null;
        return vdmLines;
    }

    public static final void writeLines(BufferedWriter writer, VdmLine[] vdmLines)
        throws IOException {
        if(vdmLines.length == 0){
            writer.close();
            System.err.println("Warning: writeLines recieved an array of 0 length");
            return; 
        }
        int counter = 0;
        int flushperiod = 5000;
        writer.write(vdmLines[0].getHeader());
        writer.newLine();
        writer.flush();
        StringBuffer buffer = new StringBuffer(500000);
        for (int i = 0; i < vdmLines.length; i++) {
            buffer.append(vdmLines[i].toCsvString());
            buffer.append("\n");
            counter++;
            if (counter % flushperiod == 0 || counter == (vdmLines.length - 1)) {
                writer.write(buffer.toString());
                writer.flush();
                buffer.delete(0, buffer.length());
            }
        }
        buffer = null;
        writer.close();
    }


}
