package models.messaging.nibss;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;


/**
 * 
 * @author CodeSchool
 */
public class NibssSocketHelper {
	private Socket socket;

	public NibssSocketHelper(String Endpoint, int port) throws IOException {
		this.socket = new Socket(Endpoint, port);
	}

	public void disconnect() throws IOException {
		if (this.socket.isConnected()) {
			this.socket.close();
		}
	}

	// / Sends data
	public boolean sendData(byte[] iso) throws IOException {
		if (this.socket.isConnected()) {
			byte[] toSend = new byte[iso.length + 2];
			long length = (long) iso.length;
			toSend[0] = (byte) (length >> 8);
			toSend[1] = (byte) length;
			System.arraycopy(iso, 0, toSend, 2, iso.length);
			DataOutputStream os = new DataOutputStream(this.socket.getOutputStream());
			os.write(toSend);
		}
		return true;
	}

	public byte[] sendReceive(byte[] data) {
		try {
			sendData(data);
			return getData();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	// / Load out all the data
	public byte[] getData() throws IOException {
		byte[] dataLen = new byte[2];
		DataInputStream is = new DataInputStream(this.socket.getInputStream());
		is.readFully(dataLen);
		int len = dataLen[0] * 256 + dataLen[1];
		byte[] buffer = new byte[len];
		is.readFully(buffer, 0, len);
		return buffer;
	}


}
