package net.arnx.fextio.parsers;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class CsvReader implements AutoCloseable {
	private final DsvStreamReader creader;
	private final boolean skipEmptyLines;
	
	public CsvReader(Path path, Charset charset) throws IOException {
		this(Files.newBufferedReader(path, charset), false, true, true);
	}
	
	public CsvReader(InputStream in, Charset charset) throws IOException {
		this(in, charset, false, true, false);
	}
	
	public CsvReader(InputStream in, Charset charset, boolean skipEmptyLines, boolean escape, boolean parallel) throws IOException {
		this(new InputStreamReader(in, charset), skipEmptyLines, escape, parallel);
	}
	
	public CsvReader(Reader reader) throws IOException {
		this(reader, false, true, false);
	}
	
	public CsvReader(Reader reader, boolean skipEmptyLines, boolean escape, boolean parallel) throws IOException {
		this.creader = new DsvStreamReader(reader, ',', escape, parallel);
		this.skipEmptyLines = skipEmptyLines;
	}
	
	public boolean next(List<String> list) throws IOException {
		while (creader.next()) {
			String text = creader.text();
			if (text != null) {
				list.add(text);
			} else if (skipEmptyLines) {
				continue;
			}
			
			if (creader.eol()) {
				return true;
			}
		}
		return false;
	}
	
	public int getLine() {
		return creader.line();
	}
	
	public int getRow() {
		return creader.row();
	}
	
	@Override
	public void close() throws IOException {
		creader.close();
	}
}
