package eu.dnetlib.data.collector.plugins.mongo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class MongoDumpIterator implements Iterator<String> {

	private final BufferedReader inputStream;
	private String currentLine = null;

	public MongoDumpIterator(final FileReader inputStream) {
		this.inputStream = new BufferedReader(inputStream);
		this.currentLine = getNextLine();
	}

	@Override
	public boolean hasNext() {
		return currentLine != null;

	}

	@Override
	public String next() {
		final String returnedString = this.currentLine;
		this.currentLine = getNextLine();
		return returnedString;
	}

	@Override
	public void remove() {
		// TODO Auto-generated method stub

	}

	private String getNextLine() {
		try {
			String input = inputStream.readLine();
			while (input != null) {
				JsonElement jElement = new JsonParser().parse(input);
				JsonObject jobject = jElement.getAsJsonObject();
				if (jobject.has("body")) { return jobject.get("body").getAsString(); }
				input = inputStream.readLine();
			}
			return null;

		} catch (IOException e) {
			return null;
		}
	}
}
