package de.lazyzero.NazeWiiConf.utils;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class NazePort {
	
	private SerialPort serialPort;
	InputStreamReader isr;
	private InputStream in;
	private OutputStream os;
	BufferedReader out;
	private int baud = 9600;
	private String port;
	private boolean portOpened = false;
	private CommPort commPort;
	
	public NazePort(String port, int baud) {
		this.port = port;
		this.baud = baud;
	}
	
	public void openPort() throws Exception{
		CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(port);
		commPort = portIdentifier.open("LightController",2000);
        
        if ( commPort instanceof SerialPort )
        {
            serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(baud,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
            
            in = serialPort.getInputStream();
            os = serialPort.getOutputStream();
           
            isr = new InputStreamReader(in);
            out = new BufferedReader(isr);
            setPortOpened(true);
        }
	}
	
	public void close() throws IOException {
		System.out.println("close Port");
		out.close();
		in.close();
		isr.close();
		os.close();
		out = null;
		in = null;
		isr = null;
		os = null;
		serialPort.close();
		commPort.close();
		serialPort = null;
		commPort = null;
		setPortOpened(false);
	}
	
	public void write(byte[] command) throws IOException {
		os.write(command);
	}

	public void write(int command) throws IOException {
		os.write(command);
	}

	public String readLine() throws IOException {
		return out.readLine();
	}
	
	public int getBaud() {
		return baud;
	}

	public void setBaud(int baud) {
		this.baud = baud;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public boolean isPortOpened() {
		return portOpened;
	}

	public void setPortOpened(boolean portOpened) {
		this.portOpened = portOpened;
	}




}
