package scone.accesstracking.applet;


import scone.ras.Connection;


/**
 * ReceiverThread receives messages from RASServer.
 */
public class ReceiverThread extends Thread {
    private Connection con;
    private String inputLine;
    private LogApplet logApplet;

    ReceiverThread(Connection con, LogApplet logApplet) {
        this.con = con;
        this.logApplet = logApplet; // reference to LogApplet
    }

    /**
     * This method receives messages from RASServer and calls the
     * corresponding method of LogApplet before it waits for the
     * next transmission
     * <P>
     * Some valid commands are:<BR>
     * command=openurl<BR>
     * command=bringtofront<BR>
     * @see scone.accesstracking.FrameAccessTest for more examples.
     */
    public void run() {
        try {
            while ((inputLine = con.read()) != null) {
                // System.out.println("ReceiverThread: Received: " + inputLine);
                if (inputLine.startsWith("AccessEventExisted=")) {
                    logApplet.statusSaverReceived(inputLine);
                } else if (inputLine.startsWith("command=openurldelayed")) {  // Open new URL delayed a bit. Using JavaScript
                    logApplet.openURLDelayed(getParameter(inputLine, "parameter1"));
                } else if (inputLine.startsWith("command=openurl")) {       // open new URL immediately. Using AppletContext
                    logApplet.openURL(getParameter(inputLine, "parameter1"),
                            getParameter(inputLine, "parameter2"));
                } else if (inputLine.startsWith("command=bringtofront")) {  // All commands are lowercase!
                    logApplet.bringToFront();
                } else if (inputLine.startsWith("command=closebrowser")) {
                    logApplet.closeBrowser();
                } else if (inputLine.startsWith("command=blurbrowser")) {
                    logApplet.blurBrowser();
                } else if (inputLine.startsWith("command=anyfunction")) {
                    logApplet.anyFunction(getParameter(inputLine, "parameter1"));
                }
            }
        } catch (Exception e) {}
    }

    /**
     * Look for a substring paramName in inputLine and return the
     * string between the next "=" and "\n"
     *
     * @param inputLine The text string containing parameters
     * @param paramName The substring to search for
     */
    private String getParameter(String inputLine, String paramName) {
        int startPos;
        int endPos;

        if (inputLine.indexOf("\n" + paramName + "=") > -1) {
            startPos = inputLine.indexOf("\n" + paramName + "=")
                    + paramName.length() + 2;
            endPos = inputLine.indexOf("\n", startPos);
            return inputLine.substring(startPos, endPos);
        } else {
            System.out.println("Required Parameter " + paramName + " not found in String " + inputLine);
            return "";
        }
    }

}
