package io.domisum.lib.auxiliumlib;

import io.domisum.lib.auxiliumlib.annotations.API;

import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;

public class FileLineStream
{
	
	private final Deque<String> currentLines = new ArrayDeque<>();
	private final Iterator<String> iterator;
	
	
	// INIT
	public FileLineStream(File file)
	{
		try
		{
			iterator = Files.lines(file.toPath()).iterator();
		}
		catch(IOException e)
		{
			throw new UncheckedIOException(e);
		}
	}
	
	
	// STREAM
	@API
	public String discardLinesUntil(String marker)
		throws IOException
	{
		while(currentLines.size() > 0)
		{
			String cl = currentLines.removeFirst();
			if(cl.contains(marker))
				return cl;
		}
		
		return findLineInIterator(marker, false);
	}
	
	@API
	public String findLine(String marker)
		throws IOException
	{
		for(String cl : currentLines)
			if(cl.contains(marker))
				return cl;
		
		return findLineInIterator(marker, true);
	}
	
	private String findLineInIterator(String marker, boolean addLinesToCurrent)
		throws IOException
	{
		while(iterator.hasNext())
		{
			String line = iterator.next();
			
			if(addLinesToCurrent)
				currentLines.add(line);
			if(line.contains(marker))
				return line;
		}
		
		throw new IOException(PHR.r("Could not find line containing '{}'", marker));
	}
	
	@API
	public Iterator<String> iterateAndDiscard()
	{
		return new LineIterator();
	}
	
	private class LineIterator
		implements Iterator<String>
	{
		
		@Override
		public boolean hasNext()
		{
			if(currentLines.size() > 0)
				return true;
			
			return iterator.hasNext();
		}
		
		@Override
		public String next()
		{
			if(currentLines.size() > 0)
				return currentLines.removeFirst();
			
			return iterator.next();
		}
		
	}
	
}

@@ -82,16 +82,42 @@
 s.API;%0A%0A
+import java.io.Closeable;%0A
 import j
@@ -306,38 +306,130 @@
 or;%0A
-%0Apublic class FileLineStream%0A%7B
+import java.util.stream.Stream;%0A%0Apublic class FileLineStream%0A%09implements Closeable%0A%7B%0A%09%0A%09private final Stream%3C?%3E closeable;
 %0A%09%0A%09
@@ -596,24 +596,31 @@
 %0A%09%09%7B%0A%09%09%09
-iterator
+var linesStream
  = Files
@@ -640,16 +640,71 @@
 oPath())
+;%0A%09%09%09closeable = linesStream;%0A%09%09%09iterator = linesStream
 .iterato
@@ -786,16 +786,98 @@
 %09%7D%0A%09%7D%0A%09%0A
+%09@Override%0A%09public void close()%0A%09%09throws IOException%0A%09%7B%0A%09%09closeable.close();%0A%09%7D%0A%09%0A
 %09%0A%09// ST

Add file handle closing to FileLineStream