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

import CommonFunctions.debugPrinter;
import javax.microedition.io.Connector;
import javax.microedition.io.DatagramConnection;
import javax.microedition.io.Datagram;
import utility.StringUtil;

/* class communication RecvThread
 * Receives data from other vehicles via UDP, decrypts and then deserializes it.
 */
public class UDPRecvThread extends Thread {

    private DatagramConnection socket;
    private int portNumber;

    public UDPRecvThread(int portno) {

        portNumber = portno;

    }

    @Override
    public void run() {

        while (true) {

            try {

                //receive data from socket
                byte[] buf = new byte[256];


                socket = (DatagramConnection) Connector.open("datagram://:" + portNumber);

                Datagram packet = socket.newDatagram(buf, buf.length);
                socket.receive(packet);


                //copy the data into a new byte array
                byte[] tmp = new byte[packet.getLength()];
                for (int i = 0; i < packet.getLength(); i++) {
                    tmp[i] = packet.getData()[i];
                }

                debugPrinter.printLine("RECEIVED: " + new String(tmp));

                //address looks likes this: datagram://10.80.148.246:4446
                String ipaddress = packet.getAddress().toString();
                String[] tmpString = StringUtil.split(ipaddress, "//");
                String tmpAddress[] = StringUtil.split(tmpString[1], ":");
                String finalAddress = tmpAddress[0];

                //decrypt data
                byte[] output = encryption.pbeEncryption.decrypt(tmp);

                debugPrinter.printLine("CLEAR TEXT: " + new String(output));

                //deserialize
                Deserialize.deserializeHashContext(new String(output), finalAddress);
                socket.close();

            } catch (Exception ie) {
                ie.printStackTrace();

                return;
            }
        }
    }
}
