import com.sun.kjava.*;
import java.io.*;

/** Test program which accesses Palm Address Book in a Read Only
 *Fashion. 
 *
 * This program brings up a viewing area showing one address book entry at a
 * time in a scrolling text box.  There are three buttons at the bottom of
 * the screen, a <code>next</code>, <code>previous</code>, and
 * <code>exit</code> button. 
 */

public class AddrView extends Spotlet {

    // the single Graphics object
    Graphics g = Graphics.getGraphics();
    // our buttons
    private static Button exitButton;
    private static Button nextButton;
    private static Button previousButton;

    // the database we are looking at
    private Database db;

    // a record from the database
    byte[] record;

    // we will convert the byte array into a DataInputStream, so input will
    // be more straightforward
    ByteArrayInputStream byteIn;
    DataInputStream dataIn;
    
    // scrolling box to hold our output
    BasicScrollTextBox scrollText;
    // the current record index
    int currentAddressIndex = 0;

    // An Address Record from the Address book
    AddressRecord addressRecord = new AddressRecord();

    /** Start the spotlet */
    public static void main(String[] args) {
	(new AddrView()).register(NO_EVENT_OPTIONS);
    }

    /** Create the Spotlet */
    public AddrView() {
	// initialize the gui components
	scrollText = new BasicScrollTextBox("",
					    5, 15, 150, 125);
	exitButton = new Button("Exit",139,145);
	nextButton = new Button("Next",50,145);
	previousButton = new Button("Previous",2,145);
	previousButton.setEnabled(false);

	g.clearScreen();
	exitButton.paint();
	nextButton.paint();
	previousButton.paint();
	// open the database
	db = new Database(convertTypeToInt("DATA"),
			convertTypeToInt("addr"),
			Database.READONLY);
	if (!db.isOpen()) {
	    scrollText.setText("Couldn't open Database");
	} else if (db.getNumberOfRecords() > 0) {
	    readAddressRecord(currentAddressIndex);
	    // set the text to the scrolling output
	    scrollText.setText(addressRecord.toCompressedFormattedString());
	} else if (db.getNumberOfRecords() == 0) {
	    scrollText.setText("Address Book is empty...");
	    nextButton.setEnabled(false);
	    nextButton.paint();
	} else if (db.getNumberOfRecords() == 1) {
	    nextButton.setEnabled(false);
	}
	
	// paint the screen
	g.clearScreen();
	g.drawString(" Palm Address Book Record " +
		     (currentAddressIndex + 1) +
		     " of " +
		     db.getNumberOfRecords() +
		     " ",
		     10, 0, Graphics.INVERT);
	exitButton.paint();
	previousButton.paint();
	scrollText.paint();
	nextButton.paint();
    }


    /** Read a single address record from the database.
     * @param index the index of the record to be read
     */
    protected void readAddressRecord(int index) {
	// read the record
	record = db.getRecord(index);
	// convert it into a DataInputStream
	byteIn = new ByteArrayInputStream(record, 0, record.length);
	dataIn = new DataInputStream(byteIn);
	// now read the data into the AddressRecord
	try {
	    //translates the body of the record	    
	    addressRecord.readData(dataIn);  
	    dataIn.close();
	  } catch (IOException ioe) {
	      scrollText.setText("ERROR: Unable to read record " +
				 index +
				 "...");
	  }

    }
    
    /** Convert a four character string to it's byte values */
    public int convertTypeToInt(String type) {
	byte[] b = type.getBytes();
	return ((int)b[0])*(256*256*256)+
            ((int)b[1])*(256*256)+
            ((int)b[2])*(256)+
            ((int)b[3]);
    }
    
    /**
     * Draw the screen
     */
    private void paint() {
	g.clearScreen();
	// Draw GUI controls and buttons
	exitButton.paint();
	nextButton.paint();
	previousButton.paint();
	scrollText.paint();
    }
    
    /**
     * Handle a pen down event.
     */
    public void penMove(int x, int y) {
	if (scrollText.contains(x,y)) {
	    scrollText.handlePenMove(x,y);
	}
    }
    
    /**
     * Handle a pen down event.
     */
    public void penDown(int x, int y) {
	// exit button
	if (exitButton.pressed(x,y)) {
	    System.exit(0);

        // user wants to scroll text
	} else if (scrollText.contains(x,y)) {
	    scrollText.handlePenDown(x,y);
        // next button pressed
	} else if (nextButton.pressed(x,y)) {
	    // read the next record
	    readAddressRecord(++currentAddressIndex);
	    // update buttons based on where we are in the database
	    if (currentAddressIndex == db.getNumberOfRecords() - 1) {
		nextButton.setEnabled(false);
		nextButton.paint();
	    } else if (!previousButton.isEnabled()) {
		previousButton.setEnabled(true);
		previousButton.paint();
	    }
	    scrollText.setText(addressRecord.toCompressedFormattedString());
	    scrollText.paint();
	    g.drawString(" Palm Address Book Record " +
			 (currentAddressIndex + 1) +
			 " of " +
			 db.getNumberOfRecords() +
			 " ",
			 10, 0, Graphics.INVERT);
        // next button pressed
	} else if (previousButton.pressed(x,y)) {
	    // read the previous record
	    readAddressRecord(--currentAddressIndex);
	    // update buttons based on where we are in the database
	    if (currentAddressIndex == 0) {
		previousButton.setEnabled(false);
		previousButton.paint();
	    } else if (!nextButton.isEnabled()) {
		nextButton.setEnabled(true);
		nextButton.paint();
	    }
	    scrollText.setText(addressRecord.toCompressedFormattedString());
	    scrollText.paint();
	    g.drawString(" Palm Address Book Record " +
			 (currentAddressIndex + 1) +
			 " of " +
			 db.getNumberOfRecords() + " ",
			 10, 0, Graphics.INVERT);
	}
    }
	    
}


