package at.ac.tuwien.lsdc.util;

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

import at.ac.tuwien.lsdc.types.Application;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

public class CSVParser {
	public static LinkedList<Application> parseFile(File csvFile)
			throws IOException {
		CSVReader reader = new CSVReader(new FileReader(csvFile), ';',
				CSVWriter.NO_QUOTE_CHARACTER);
		List<String[]> file = reader.readAll();
		LinkedList<Application> apps = new LinkedList<Application>();
		// start at 1 to ignore header
		for (int i = 1; i < file.size(); i++) {
			String[] line = file.get(i);
			if (line.length != 5) {
				reader.close();
				throw new IOException(
						"CSVParser: Not right amount of elements in line " + i
								+ 1);
			} else {
				try {
					Application a = parseLine(line);
					apps.add(a);
				} catch (NumberFormatException e) {
					reader.close();
					throw new IOException("Couldn't parse line");
				}
			}
		}
		reader.close();
		return apps;
	}

	private static Application parseLine(String[] appStr)
			throws NumberFormatException {
		long timestamp = Long.parseLong(appStr[0]);
		int size = Integer.parseInt(appStr[1]);
		int ram = Integer.parseInt(appStr[2]);
		int cpu = Integer.parseInt(appStr[3]);
		int duration = Integer.parseInt(appStr[4]);
		Application app = new Application(timestamp, size, ram, cpu, duration);
		return app;
	}

}
