package basics.filesystem.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import basics.application.Binder;
import basics.testing.Test;

/**
 * @author kst
 */
public class LineReader
{
String                 charset     = "utf-8";
private String         fileName    = "";
private BufferedReader brin        = null;
private String         currentLine = null;

public LineReader(String fileName)
{
   this.fileName = fileName;
}

public LineReader(File file)
{
   this.fileName = file.getAbsolutePath();
}

/**
 * ACHTUNG hasLine verschiebt den filepointer! nach hasLine muss er nextLine angefragt werden, wird
 * mehrfach hasLine abgerufen, bevor nextLine angerufen wird, dann ueberpringen wir zeilen!
 * @return
 */
public boolean hasLine()
{
   currentLine = read();
   if(currentLine != null)
   {
      return true;
   }
   return false;
}

public String nextLine()
{
   if(currentLine != null)
   {
      String line = new String(currentLine);
      currentLine = null;
      return line;
   }
   else
   {
      return read();
   }
}

public String nextLineTrimNotNull()
{
   String s = nextLine();
   return s == null ? "" : s.trim();
}

private String read()
{
   try
   {
	   
      //return new String(brin.readLine().getBytes(), "utf-8");
	   return brin.readLine();
   }
   catch(Exception e) // Null+IO
   {
      return null;
   }
}

public boolean open()
{
   if(new File(fileName).exists())
   {
      try
      {    	 
    	 //brin = new BufferedReader(new FileReader(fileName));
    	 //by[j]
    	 FileInputStream fis = new FileInputStream(fileName);
    	 InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
         brin = new BufferedReader(isr);
         return true;
      }
      catch(IOException e)
      {
         try
         {
            brin.close();
         }
         catch(IOException ex)
         {
         }
      }
   }
   return false;
}

public void close()
{
   try
   {
      brin.close();
   }
   catch(IOException ex)
   {
   }
}

public static void unittest()
{
   File p = new File(Binder.getBasedir(), "work/3lines.txt");
   LineReader l = new LineReader(p);
   Test.assertTrue(l.open(), "Can't open test file 3lines.txt");
   int x = 0;
   while(l.hasLine())
      x++;
   Test.assertTrue(x == 3, "Expected 3 lines in 3lines.txt not " + x);
   l = new LineReader(p);
   Test.assertTrue(l.open(), "Can't open test file 3lines_2comments.txt");
   x = 0;
   while(l.hasLine())
      x++;
   Test.assertTrue(x == 3, "Expected 3 lines in 3lines.txt not " + x);
}
}
