package hardware.c328.testing;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class SerialPortDataHandler implements Runnable {

	private SerialPort serialPort;
	InputStream in;
	OutputStream outputStream;
	FileOutputStream fos;
	DataOutputStream dos;
	private byte[] picture;
	private File file = new File("test.jpg");

	@Override
	public void run() {
		try {
			String port = "/dev/ttyUSB0";
			CommPortIdentifier portIdentifier = CommPortIdentifier
					.getPortIdentifier(port);
			CommPort commPort = portIdentifier.open(this.getClass().getName(),
					2000);
			if (commPort instanceof SerialPort) {
				serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
						SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
				in = serialPort.getInputStream();
				outputStream = serialPort.getOutputStream();
			}
			byte[] buffer = new byte[4096];
			int data;
			int len = 0;
			while ((data = in.read()) > -1) {
				if (data == '\n') {
					String msg = new String(buffer, 0, len);
					if (msg.indexOf(':') > 0) {
						int start = msg.indexOf(':') + 1;
						String sz = msg.substring(start);
						try {
							Integer size = Integer.parseInt(sz.trim());
							picture = new byte[size.intValue()];
						} catch (NumberFormatException nfe) {
							nfe.printStackTrace();
						}
						System.out.println("Picture size: " + sz);
					}
					else {
						System.out.println(msg);
					}
					len = 0;
					buffer = new byte[4096];
				} else if (data == '@') {
					for(int i = 0; i < picture.length; i++) {
						picture[i] = (byte) in.read();
					}
					System.out.println("Picture data received. Writing to file");
					fos = new FileOutputStream(file);
					dos = new DataOutputStream(fos);
					dos.write(picture);
					break;
				}

				else {
					buffer[len++] = (byte) data;
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				serialPort.close();
				dos.close();
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

