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

import CommonFunctions.debugPrinter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

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

    private DatagramSocket socket;

    public UDPRecvThread(DatagramSocket sock) {
        socket = sock;

    }

    @Override
    public void run() {

        while (true) {

            try {

                //receive data from socket
                byte[] buf = new byte[512];
                DatagramPacket packet = new DatagramPacket(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));

                String ipaddress = packet.getAddress().toString();


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

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

                //deserialize
                Deserialize.deserializeHashContext(new String(output), ipaddress);

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