/*
 * 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;
import java.net.InetAddress;
import java.util.Enumeration;
import mdot.Main;
import structures.NeighborStateDB;
import structures.NeighborStateDBValue;

/* class UDPSendThread
 * Serializes vehicle hash context, encrypts string using pbe encryption and
 * sends it to all the vehicles in the neighbor database via UDP.
 */
public class UDPSendThread extends Thread {

    private int time = 0;
    private DatagramSocket socket;
    private NeighborStateDB neighbors = Main.neighbors;

    public UDPSendThread(DatagramSocket sock, int ticktime) {
        socket = sock;
        time = ticktime;

    }

    @Override
    public void run() {

        while (true) {


            try {

                //Serialize MY data
                String mydata = null;
                mydata = Serialize.serializeHashContext();
                debugPrinter.printLine("SERIALIZED: " + mydata);

                Enumeration<NeighborStateDBValue> enKeys = neighbors.neighborDatabase.elements();
               
                //for all my neighbors..
                while (enKeys.hasMoreElements()) {
                    NeighborStateDBValue tmpDB = enKeys.nextElement();

                    //get the ipaddress,password and port to use
                    String ipAddress = tmpDB.getIPAddress();
                    String password = tmpDB.getPasswd();
                    int port = tmpDB.getPort();
                    InetAddress address = InetAddress.getByName(ipAddress.replace("/", ""));

                    //---encypt using destination password
                    byte [] encryptData = encryption.pbeEncryption.encrypt(password, mydata);

                    //create a buffer that is the size of data
                    byte[] buf = new byte[encryptData.length];
                    //byte[] buf = new byte[mydata.getBytes().length];

                    //send data
                    buf = encryptData;
                    DatagramPacket packet = new DatagramPacket(buf, buf.length, address, port);
                    socket.send(packet);

                    debugPrinter.printLine("SENT: " + new String(buf));
                    
           
                }
                //debugPrinter.printLine("sendThread -- SLEEPING!");
                sleep(time);
                yield();

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


    }
}