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

import CommonFunctions.RandomSelectSuperNode;
import database.CoreDatabase;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import javax.microedition.io.SocketConnection;
import javax.microedition.io.Connector;
import java.util.Vector;
import mdot.Main;
import structures.Constants;
import structures.HashContext;
import structures.RegionalManagerObject;
import structures.SuperNodeObject;
import utility.StringUtil;
import utility.J2SEToJ2MEUtil;

/**
 *class TCPCommunicationThread
 * Every x seconds, randomly selected a supernode and with it's response,
 * create a vector of regional managers in the area where this vehicle is located.
 *
 */
public class SNCommunicationThread extends Thread {

    private SocketConnection tcpSocket;
    private String stringSendToSupernode;
    private int sleepTime = -1;

    public SNCommunicationThread(int tickTime) {

        HashContext me = Main.getMe();
        stringSendToSupernode = Main.meString + Constants.DELIMITER_FOR_VIN + me.GetObjectAsString(Constants.HASH_LATITUDE) + Constants.DELIMITER_FOR_VIN + me.GetObjectAsString(Constants.HASH_LONGITUDE) + "\n";
        sleepTime = tickTime;

    }

    @Override
    public void run() {
        while (true) {
            try {

                SuperNodeObject tmpSuper = RandomSelectSuperNode.RandomSelect();

                try {

                    System.out.println("selected supernode in node= " + tmpSuper.getID());

                    tcpSocket = (SocketConnection) Connector.open("socket://"
                            + tmpSuper.getIPAddress() + ":" + Integer.parseInt(tmpSuper.getNode_tcp_portNo()));

                    OutputStream out = tcpSocket.openOutputStream();

                    out.write(stringSendToSupernode.getBytes());
                    out.close();

                    System.out.println("sent to supernode from node= " + stringSendToSupernode);

                    InputStream inStream = tcpSocket.openInputStream();

                    DeserializeTCPInputStreamFromSuperNode(inStream);

                    inStream.close();
                    tcpSocket.close();

                } catch (Exception ex) {
                    System.out.println(ex.toString());
                    //return;
                }

                sleep(sleepTime);
                yield();
                
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /* Reads the response from the Supernode and creates a vector
     * of regional managers that are in the same area as this vehicle.
     * Puts the vector of reginal managers in the CoreDatabase.
     */
    public void DeserializeTCPInputStreamFromSuperNode(InputStream input) {

        String inputString = null;

        try {

            InputStreamReader inReader = new InputStreamReader(input);

            inputString = J2SEToJ2MEUtil.readStrFrmInputStream(inReader);
            inReader.close();

            inputString = StringUtil.replace(inputString, "\n", "");
            System.out.println("receive regional manager = " + inputString);

            if (inputString.equals("null")) {
                inputString = null;
            } else {
                CoreDatabase.rmVector = new Vector();
            }

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

        try {
            //Construct a vector of regional managers and insert into database
            if (inputString != null) {
                String[] entries = StringUtil.split(inputString, Constants.DELIMITER_ENTRY);

                for (int i = 0; i < entries.length; i++) {
                    String entry = entries[i];
                    String name = StringUtil.split(entry, Constants.DELIMITER_FOR_VIN)[0];
                    String ipAddress = StringUtil.split(entry, Constants.DELIMITER_FOR_VIN)[1];
                    String portno = StringUtil.split(entry, Constants.DELIMITER_FOR_VIN)[2];
                    CoreDatabase.rmVector.addElement(new RegionalManagerObject(name, ipAddress, portno));
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
