/*
*/

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

public class SerialDrawReader2 implements SerialPortEventListener {
	static CommPortIdentifier portId;
	static Enumeration portList;
	
	InputStream inputStream;
	OutputStream outputStream;
	SerialPort serialPort;
	Thread readThread;
	
	SerialDrawPanel theCallingComponent; // How do I abstract this?
    
	 // ASCII Constants
//	static Byte StartOfTransmission = new Byte(new Integer(201).byteValue());
//	static Byte EndOfTransmission = new Byte(new Integer(202).byteValue());
//	static Byte PositiveAcknowledgement = new Byte(new Integer(203).byteValue());
//	static Byte NegativeAcknowledgement = new Byte(new Integer(204).byteValue());
	static Byte AreYouThere = new Byte(new Integer(205).byteValue());
	static Byte ReadyForTransmission = new Byte(new Integer(206).byteValue());
	    

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

	public SerialDrawReader2(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();
					outputStream = serialPort.getOutputStream();
					
			        } 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");	
			        }
			
				// Prime the pump
				sendSerial(ReadyForTransmission);
				System.out.println("Ready For Transmission Sent");
	
	                }
	            }
	        }
    	}
	
	public void sendSerial(Byte byteToSend)
	{
		try
		{
	    		outputStream.write(byteToSend.intValue());		
	    	}
	    	catch (IOException e)
	    	{}
	}

    	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];
            			byte[] passBuffer = new byte[20];
            			int passBufferCount = 0;

            			int numBytes = 0;
				try 
				{
					while (inputStream.available() > 0) 
					{
						numBytes = inputStream.read(readBuffer);    
					}
					
					// All Read, Call For More
					sendSerial(ReadyForTransmission);
					System.out.println("Ready For Transmission Sent");
					
					//System.out.print(new String(readBuffer, "US-ASCII"));
					for (int i = 0; i < numBytes; i++)
					{
						
						if (AreYouThere.byteValue() == readBuffer[i])
						{
							System.out.println("Are You There Received");
							sendSerial(ReadyForTransmission);
							System.out.println("Ready For Transmission Sent");
						}
						
						 
						if (readBuffer[i] != 0)
						{
							passBuffer[passBufferCount] = readBuffer[i];
							passBufferCount++;
						}
					}
					if (passBufferCount > 0)
					{
						theCallingComponent.doDrawing(passBuffer, numBytes);				
					}
				} 
				catch (IOException e) 
				{

				}
				break;
		}
	}
}
