
package de.ivu.elect.exchange.csv;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.commons.io.input.BOMInputStream;
import org.jsefa.csv.CsvDeserializer;

public class AutoCloseableCsvDeserializer<T> extends AbstractAutoCloseableCsvSerializing<T> {

  private final CsvDeserializer deserializer;

  public AutoCloseableCsvDeserializer(Class<T> clazz, InputStream is, CsvDescriptor csvDescriptor) {
    super(csvDescriptor);

    this.deserializer = createCsvIOFactory(clazz).createDeserializer();

    openStream(is);
  }

  protected void openStream(InputStream is) {
    try {
      deserializer.open(createReader(is));
    } catch (Exception ex) {
      throw new RuntimeException(ex.getMessage(), ex);
    }
  }

  private Reader createReader(InputStream is) {
    return new InputStreamReader(getCharsetBom().map(bom -> (InputStream) new BOMInputStream(is, bom)).orElse(is), getCharset());
  }

  public boolean hasNext() {
    return deserializer.hasNext();
  }

  public T next() {
    return deserializer.next();
  }

  @Override
  public void close() {
    deserializer.close(true);
  }
}
