/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package BodegaPOS.printer;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Daniel
 */
public class PrinterCom {
    private SerialPort serialPort;
    private InputStream inStream;
    private OutputStream out;

    public PrinterCom(String portName) {
        try {
            initComms(portName);
        } catch (PortInUseException ex) {
            Logger.getLogger(PrinterCom.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PrinterCom.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedCommOperationException ex) {
            Logger.getLogger(PrinterCom.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
	 * Initialize the comms connection
	 *
	 * @param portName
	 *            Port to use
	 * @throws IOException
	 */
	private void initComms(String portName) throws PortInUseException,
			IOException,
			UnsupportedCommOperationException {

		CommPortIdentifier portId = null;
		Enumeration portList;

		portList = CommPortIdentifier.getPortIdentifiers();

		while (portList.hasMoreElements()) {
			CommPortIdentifier nextPortId = (CommPortIdentifier) portList.nextElement();
			if (nextPortId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
				if (nextPortId.getName().equalsIgnoreCase(portName)) {
					portId = nextPortId;
					// break;
				}
			}
		}

		if (portId == null) {
			// This implies that a port identified by the spotfinder is not accessible via
			// rxtx. Under windows this never happens, but under Linux it seems to happen
			// when the port is in use, so throw a PortInUseException
			throw new PortInUseException();
		}

		serialPort = (SerialPort) portId.open("Flasher", 2000);

		try {
			serialPort.disableReceiveThreshold();
			serialPort.enableReceiveTimeout(3000);

			serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
					SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
		} catch (UnsupportedCommOperationException e) {
			throw new IOException(e.getMessage());
		}

		inStream = serialPort.getInputStream();
		out = serialPort.getOutputStream();
	}

	/**
	 * Close the comms connection
	 *
	 * @throws IOException
	 */
	public void closeComms() throws IOException {
		inStream.close();
		out.close();
		serialPort.close();
	}

	private void sendBootloaderCommand(byte[] bytes) throws IOException {
		out.write(bytes);
	}
    
    public void send(byte[] bytes)throws IOException {
		out.write(bytes);
	}
   
}
