package network;


import models.messaging.nibss.Globals;
import models.messaging.nibss.NibssIsoProcessor;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;

import android.annotation.TargetApi;
import android.os.Build;
import android.util.Log;

public class NibssSocketManager {
	private Socket socket;

	public NibssSocketManager(Socket socket) throws IOException {
		this.socket = socket;
	}

	public void disconnect() throws IOException {
		if (this.socket.isConnected()) {
			this.socket.close();
		}
	}

	// / Sends data
	public boolean sendData(byte[] data) throws IOException {
		if (this.socket.isConnected()) {
			DataOutputStream os = new DataOutputStream(
					this.socket.getOutputStream());
			os.write(data);
		}
		return true;
	}

	// / Load out all the data
	public byte[] getData() { // throws IOException {

		byte[] buffer = new byte[1024];
		int count = 0;

		try {

			DataInputStream is = new DataInputStream(
					this.socket.getInputStream());

			while (is.available() > 0) {

				buffer[count++] = is.readByte();

				if (count >= buffer.length - 1) {

					resize(buffer);
				}

			}

			byte[] returnbuffer = new byte[count - 2];
			System.arraycopy(buffer, 2, returnbuffer, 0, count - 2);

			return returnbuffer;
		} catch (Exception e) {
			Log.i("PayPadISOERROR", "Internet connection lost");

		}

		return new byte[0];
	}

	@TargetApi(Build.VERSION_CODES.KITKAT)
	public byte[] receive() {
		byte[] lenData = new byte[2];
		byte[] receivedData = null;
		int dataLen;
		try {
				DataInputStream is = new DataInputStream(
					this.socket.getInputStream());
				is.readFully(lenData, 0, 2);
				dataLen = ((int) (0xFF & lenData[0])) * 256
						+ (int) (0xFF & lenData[1]);
				receivedData = new byte[dataLen];
				is.readFully(receivedData, 0, dataLen);

		} catch (SocketTimeoutException e) {

			NibssIsoProcessor.reversal(Globals.purchaseRequest, Globals.TSK);
			return new byte[0];
		} catch (IOException ex) {

			ex.printStackTrace();
			
			NibssIsoProcessor.reversal(Globals.purchaseRequest, Globals.TSK);
			return new byte[0];
		} catch (Exception ex) {

			ex.printStackTrace();
			
			NibssIsoProcessor.reversal(Globals.purchaseRequest, Globals.TSK);
			return new byte[0];
		}
		return receivedData;
	}

	public byte[] _getData() throws IOException {

		byte[] buffer = new byte[1024];
		DataInputStream is = new DataInputStream(this.socket.getInputStream());

		int available = is.available();

		if (available > 0) {
			int read = is.read(buffer);
		}

		return buffer;

	}

	private void resize(byte[] buffer) {
		int m_Size = 2 * buffer.length;
		int presentsize = buffer.length;

		byte[] temp = buffer;
		buffer = new byte[m_Size];

		for (int i = 0; i <= presentsize - 1; i++) {

			buffer[i] = temp[i];

		}

	}

}
