/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.shtrih.fiscalprinter.port;

import jpos.*;
import java.io.*;
import org.apache.log4j.*;
import javax.microedition.io.*;

/**
 *
 * @author swex
 */
public class BTPrinterPort implements PrinterPort {

    private String portName;
    private InputStream in = null;
    private OutputStream out = null;
    private StreamConnection conn = null;
    private static Logger logger = Logger.getLogger(BTPrinterPort.class);

    public Object getConnection()
            throws Exception {
        return conn;
    }
    
    public void open() throws Exception {
        if (portName.equals("")) {
            throw new Exception("Wrong port name");
        }
        if (conn == null) 
        {
            conn = (StreamConnection) Connector.open(portName);
            in = conn.openInputStream();
            out = conn.openOutputStream();
        }
    }

    public void close()
            throws Exception {
        logger.debug("close");
        in.close();
        out.close();
        conn.close();

        conn = null;
        logger.debug("close: OK");
    }

    public void setPortName(String portName)
            throws Exception {
        logger.debug("setPortName(" + portName + ")");
        if (!this.portName.equalsIgnoreCase(portName)) {
            close();
            this.portName = portName;
        }
    }

    public int getOpenTimeout() {
        return 0;
    }

    public void readAll() throws Exception {
        int len = in.available();
        if (len > 0) {
            byte[] data = new byte[len];
            in.read(data, 0, len);
        }
    }

    public int readByte() throws Exception {
        return in.read();
    }

    public byte[] readBytes(int len) throws Exception {
        byte data[] = new byte[len];
        in.read(data, 0, len);
        return data;
    }

    public void setBaudRate(int baudRate) throws Exception {
    }

    public void setOpenTimeout(int openTimeout) {
    }

    public void write(byte[] b) throws Exception {
        out.write(b);
    }

    public void write(int b) throws Exception {
        out.write(b);
    }

    public void setTimeout(int timeout) {
    }
}
