/*
*/

import java.io.*;
import java.util.*;
import javax.comm.*;
import javax.swing.*;

public class SerialDrawReader implements SerialPortEventListener {
    static CommPortIdentifier portId;
    static Enumeration portList;

    InputStream inputStream;
    SerialPort serialPort;
    Thread readThread;
    
    SerialDrawPanel theCallingComponent; // How do I abstract this?
    

//    public static void main(String[] args) {
//	SerialDrawReader reader = new SerialDrawReader();
//    }

    public SerialDrawReader(SerialDrawPanel callingComponent) {
    	theCallingComponent = callingComponent;
        portList = CommPortIdentifier.getPortIdentifiers();

        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (portId.getName().equals("COM1")) {
                    

		        try {
		            serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
		        } catch (PortInUseException e) {
		        	System.out.println("Port in Use");
		        }
		        try {
		            inputStream = serialPort.getInputStream();
		        } catch (IOException e) {
		        	System.out.println("Input Stream Issue");	
		        }
			try {
		            serialPort.addEventListener(this);
			} catch (TooManyListenersException e) {
				System.out.println("Too many listeners");
			}
		        serialPort.notifyOnDataAvailable(true);
		        try {
		            serialPort.setSerialPortParams(9600,
		                SerialPort.DATABITS_8,
		                SerialPort.STOPBITS_1,
		                SerialPort.PARITY_NONE);
		        } catch (UnsupportedCommOperationException e) {
		        	System.out.println("Unsupported Comm Operation");	
		        }

                }
            }
        }


    }

    public void serialEvent(SerialPortEvent event) {
 	// Create a StringBuffer and int to receive input data.
	StringBuffer inputBuffer = new StringBuffer();
	int newData = 0;    	
    	
        switch(event.getEventType()) {
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            break;   
            
        case SerialPortEvent.DATA_AVAILABLE:
            byte[] readBuffer = new byte[20];
            int numBytes = 0;

            try {
                while (inputStream.available() > 0) {
                    numBytes = inputStream.read(readBuffer);    
                }
                //System.out.print(new String(readBuffer, "US-ASCII"));
                theCallingComponent.doDrawing(readBuffer, numBytes);

            } catch (IOException e) {}
            break;

        }
    }
}
