package commons.ui;

import java.util.StringTokenizer;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import basics.utl.FormatterUtl;
import basics.utl.SUtl;
import basics.utl.SysUtl;

public class SimpleDocument extends DefaultStyledDocument //extends ObjectDocument
{

public static final String PAT_TERM  = "freq = % of % (%), w = %";
public static final String PAT_TV    = "% %; ";
public static final int    PRECISION = 5;

public void clear()
{
   int len = -1;
   try
   {
      len = getLength();
      if(len > 0)
         remove(0, len);
   }
   catch(BadLocationException e1)
   {
      SysUtl.terror(e1, SUtl.sprint("ERR signs:% ", len));
   }
}

public void appendLine(String text)
{
   int pos = -1;
   try
   {
      pos = getLength();
      insertString(pos, text, null);
   }
   catch(Exception e)
   {
      SysUtl.terror(e, SUtl.sprint("ERR pos:% len:% ", pos, text == null ? -1 : text.length()));
   }
}

public void appendLine(String text, AttributeSet a)
{
   int pos = -1;
   try
   {
      pos = getLength();
      insertString(pos, text, a);
   }
   catch(Exception e)
   {
      SysUtl.terror(e, SUtl.sprint("ERR pos:% len:% ", pos, text == null ? -1 : text.length()));
   }
}

public void insertLine(int pos, String text)
{
   try
   {
      insertString(pos, text, null);
   }
   catch(Exception e)
   {
      SysUtl.terror(e, SUtl.sprint("ERR pos:% len:% ", pos, text == null ? -1 : text.length()));
   }
}

public void insertString(final int pos, String line, AttributeSet a) throws BadLocationException
{
//   SysUtl.tracesp("BLUE %", a==null ? "NULL" : StyleConstants.getForeground(a));
   try
   {
      super.insertString(pos, line, a);
   }
   catch(Throwable t)
   {
      SysUtl.terror(t, SUtl.sprint("ERR pos:% len:% ", pos, line == null ? -1 : line.length()));
   }
}

public synchronized void remove(int offset, int length) throws BadLocationException
{
   int signs = getLength();
   String text = getText(0, signs);
   super.remove(0, signs);
   text = SUtl.extinct(text, offset, length);
   text = FormatterUtl.removeWhitespaceTail(text);
   formatLines(text, offset);
}

void formatLines(String text, int caretPosition)
{
   StringTokenizer st = new StringTokenizer(text, "\n");
   int x = 0;
   while(st.hasMoreTokens())
   {
      String t = st.nextToken() + "\n";
      insertLine(x, t);
      x += t.length();
   }
}
}
