package lejos.pc.comm;

import java.io.*;

/**
 * Implementation of NXTComm using the the LEGO Fantom API.
 * 
 * Not yet functional.
 * 
 * Should not be used directly - use NXTCommFactory to create
 * an appropriate NXTComm object for your system and the protocol
 * you are using.
 *
 */
public class NXTCommFantom implements NXTComm {
	private NXTInfo nxtInfo;
	
	public native String[] jfantom_find();
	public native long jfantom_open(String nxt);
	public native void jfantom_close(long nxt);
	public native void jfantom_send_data(long nxt, byte [] message, int len, int replyLen);
	public native byte[] jfantom_read_data(long nxt, int len);
	
	public NXTInfo[] search(String name, int protocol) {
		String[] nxtNames = jfantom_find();
		NXTInfo[] nxtInfo = new NXTInfo[nxtNames.length];
		for(int i=0;i<nxtNames.length;i++) {
			nxtInfo[i] = new NXTInfo();
			String nxtName = nxtNames[i];
			nxtInfo[i].btResourceString = nxtName;
			nxtInfo[i].name = "Unknown";
			nxtInfo[i].protocol = NXTCommFactory.USB;
			nxtInfo[i].btDeviceAddress = "";
			if (nxtName != null) {
			    if (nxtName.length() >= 3 && nxtName.substring(0,3).equals("BTH"))
			    	nxtInfo[i].protocol = NXTCommFactory.BLUETOOTH;	
			    int startName = nxtName.indexOf("::");
			    if (startName >= 0) startName +=2;
			    int endName = -1;
			    if (startName != -1) endName = nxtName.indexOf("::", startName);
			    if (startName >= 0 && endName >= 0) {
			    	nxtInfo[i].name = nxtName.substring(startName, endName);
		            nxtInfo[i].btDeviceAddress = nxtName.substring(endName+2);
			    }
			}
		}
		return nxtInfo;
	}

	public boolean open(NXTInfo nxtInfo) {
		this.nxtInfo = nxtInfo;
		nxtInfo.nxtPtr = jfantom_open(nxtInfo.btResourceString);
		return true;
	}
	
	public void close() {
		jfantom_close(nxtInfo.nxtPtr);
	}
	
	public byte [] sendRequest(byte [] data, int replyLen) {
		jfantom_send_data(nxtInfo.nxtPtr, data, data.length, replyLen-1);
		return jfantom_read_data(nxtInfo.nxtPtr, replyLen);
	}
	
	public byte [] read() throws IOException {
		throw new IOException("Not implemented");
	}
	
	public int available() throws IOException {
		throw new IOException("Not implemented");
	}
	
	public void write(byte [] data) throws IOException {
		throw new IOException("Not implemented");
	}
	
	public OutputStream getOutputStream() {
		return null;		
	}
	
	public InputStream getInputStream() {
		return null;		
	}
	
	static {
		System.loadLibrary("jfantom");
	}

}

