package commons.collections.trie;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;



/**
 * @author kst
 */
public class DictionaryReader
{

   private File           file;

   private BufferedReader brin      = null;

   private long           startTime = 0;

   private long           currTime  = 0;

   private long           wordsRead = 0;

   public static boolean  halt      = false;


   public DictionaryReader (File file) throws Exception
   {
      if (!file.exists())
      {
         throw new Exception(file.getAbsolutePath() + " not found.");
      }
      this.file = file;
   }


   public long totalWords ()
   {
      return wordsRead;
   }


   public long totalTime ()
   {
      return currTime;
   }


   public String getFilename ()
   {
      return file.getAbsolutePath();
   }


   /**
    * reading the file, calling call back method Lex.newEntry for storing the
    * data.
    */
   public long fillTrie (ITrie lex)
   {
      lex.initializeLexReading();

      String nextLine;

      try
      {
         brin = new BufferedReader(new FileReader(file));

         startTime = System.currentTimeMillis();

         while (!halt && null != (nextLine = brin.readLine()))
         {
            lex.newEntry(nextLine.trim());

            if (++wordsRead % 50000 == 0)
            {
               System.gc();
               currTime = System.currentTimeMillis() - startTime;

               for (int i = 0; i < 42; i ++) System.out.print("\b");                  
               
               System.out.print(padl((wordsRead / 1000) + "", 4) + "kw "
                     + padl(currTime + "", 12) + "ms ");
            }
         }

         lex.finalizeLexReading();
      }
      catch (Exception e)
      {
         currTime = System.currentTimeMillis() - startTime;
         System.out.println("\nFilling trie failed, reason: " + e.toString());
         System.out.println(wordsRead + " " + currTime + " ms");
      }
      finally
      {
         try
         {
            brin.close();
         }
         catch (Exception ex)
         {
         }
      }
      return wordsRead;
   }


   private String padl (String s, int w)
   {
      s = s == null ? "" : s.trim();
      StringBuffer sb = new StringBuffer();

      for (int i = 0; i < w - s.length(); i++)
      {
         sb.append(" ");
      }

      sb.append(s);

      return sb.toString();
   }
}