package de.tud.kom.p2psim.impl.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * Reader for csv files. To use this reader you need to implement the
 * {@link #parse(String[])}.
 *
 * @author Clemens Krug
 */
public abstract class CSVReader<T>
{
    private String filename;
    private String SEP;

    public CSVReader(String filename, String SEP)
    {
        this.filename = filename;
        this.SEP = SEP;
    }


    /**
     * Reads the data into a list.
     * @return A list of the generated objects.
     */
    public List<T> readData()
    {
        List<T> data = new LinkedList<>();

        BufferedReader csv = null;
        try {
            csv = new BufferedReader(new FileReader(filename));

            while (csv.ready()) {
                String line = csv.readLine();

                if (line.contains(SEP)) {
                    String[] parts = line.split(SEP);

                    T entry = parse(parts);
                    if(entry != null) data.add(entry);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (csv != null) {
                try {
                    csv.close();
                } catch (IOException e) {
                    //nothing
                }
            }
        }

        return data;
    }

    /**
     * Parses one line of csv entries into the desired type of object.
     * @param parts The csv entries of a line.
     * @return Object of desired type.
     */
    public abstract T parse(String[] parts);
}
