import com.sun.kjava.*;

public class ReadEzDB extends Spotlet {
    
    // handle on the singleton Graphics object
    static Graphics g = Graphics.getGraphics();

    // the GUI button
    Button exitButton;
    Button readButton;
    String output="";
    String title = "Push \"Read DB\" ButtonRead to begin";
    TextBox textBox = new TextBox("", 5, 50, 125, 60);
    static int dbType = 0x457A4442; // 'EzDB'
    static int dbCreator = 0x414B414E; // 'AKAN'
    String string ="<none>";
    int length = 0;

    Database db;

    /**
     * The main method simply creates a Scribble spotlet and
     * registers its event handlers.
     */
    public static void main(String[] args) {
	(new ReadEzDB()).register(NO_EVENT_OPTIONS);
    }
    
    /**
     * Default constructor creates the GUI components and draws them.
     */
    public ReadEzDB() {
	
	// create the button
	readButton = new Button("Read DB",1,145);
	exitButton = new Button("Exit",139,145);
	paint();
    }
    
    /**
     * Draw the screen
     */
    private void paint() {
	g.clearScreen();
	g.drawString(" Read a DB Demo ", 34, 0, Graphics.INVERT);
	g.drawString(title, 10, 30);
	textBox.paint();
	// Draw GUI controls and buttons
	exitButton.paint();
	readButton.paint();
    }
    
    /**
     * Handle a pen down event.
     */
    public void penDown(int x, int y) {

	byte[] record;
	byte[] recNoNull;

	if (readButton.pressed(x,y)) {
	    // first clear our output
	    output="";
	    db = new Database(dbType, dbCreator, Database.READONLY);
	    if (db.isOpen()) {
		int recordCount = db.getNumberOfRecords();
		title="Reading DB...found " + recordCount + " items";
		for (int i=0; i < recordCount; i++) {
		    record = db.getRecord(i);
		    recNoNull = new byte[record.length - 1];
		    for (int j=0; j < record.length - 1; j++) {
			recNoNull[j] = record[j];
		    }
//  		    string = new String(recNoNull, 0, 0,
//  					recNoNull.length);
  		    string = new String(recNoNull, 0, 
  					recNoNull.length);
		    length=recNoNull.length;
		    output = output + string + '\n';
		}
		db.close();
	    }
	    textBox.setText(output);
	    paint();
	}
	else if (exitButton.pressed(x,y)) {
	    System.exit(0);
	}
    }
}
