package sivantoledo.nxt;

import java.util.concurrent.locks.*;
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;

public class Log {
  
  private static Shell shell;
  private static Text  text;
  private static Color white;
  
  /*
   * open() should only be called from the UI thread!
   */
  
  public static void open(final Image icon) {
    Display.getDefault().asyncExec(new Runnable() {
      public void run() {         
        if (shell == null) {
          Display display = Display.getDefault();
          shell = new Shell(display);
          shell.setText("NXT Log Display");
          if (icon != null) shell.setImage(icon);
          shell.setLayout( new RowLayout() );
          text = new Text(shell,
                          SWT.BORDER | SWT.MULTI | SWT.READ_ONLY | SWT.LEFT );
          white = new Color(null, 255, 255, 255);
          text.setBackground(white);
          text.setLayoutData(new RowData(display.getClientArea().width / 2, 
                                         display.getClientArea().height / 2));

          shell.pack();
          
          shell.addListener (SWT.Dispose, new Listener () {
            public void handleEvent (Event event) {
              shell = null; // so that we open another shell next time
              white.dispose();
            }
          });
          
          shell.open();
        }
      }
    });
  }

  public static void close() {
    Display.getDefault().asyncExec(new Runnable() {
      public void run() {         
        if (shell == null) {
          shell.dispose();
        }
      }
    });
  }

  public static void println(final String s) {
    System.out.println(s);
    Display.getDefault().asyncExec(new Runnable() {
      public void run() {         
        if (shell != null) {
          text.insert(s+Text.DELIMITER);
        }
      }
    });
  }

  public static void printf(final String format, final Object ... o) {
    System.out.printf(format,o);
    Display.getDefault().asyncExec(new Runnable() {
      public void run() {         
        if (shell != null) {
          text.insert(String.format(format, o)+Text.DELIMITER);
        }
      }
    });
  }
}
