/*
 * Scone - The Web Enhancement Framework
 * Copyright (c) 2004 Harald Weinreich, Volkert Buchmann, Frank Wollenweber, Torsten Haß
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package scone.usertesttool;

import java.util.ResourceBundle;
import java.util.Locale;
import java.util.Properties;

import scone.util.PersistentProperties;
import scone.netobjects.NetNode;
import scone.netobjects.NetNodeCache;

import com.ibm.wbi.RequestEvent;
import com.ibm.wbi.RequestRejectedException;
import com.ibm.wbi.protocol.http.DocumentInfo;
import com.ibm.wbi.protocol.http.HttpGenerator;
import com.ibm.wbi.protocol.http.HttpRequest;
import com.ibm.wbi.protocol.http.HttpResponse;
import com.ibm.wbi.protocol.http.beans.FormHelper;
import com.ibm.wbi.protocol.http.beans.StaticHtmlGenerator;


/**
 *
 * @author Torsten Hass
 * @author Harald Weinreich
 * @version 1.0, 11/10/2003
 */
public class UserTestToolMeg extends HttpGenerator {
 
    private scone.Plugin plugin = null;
    private static UserTestControl utc = null;

    protected static ResourceBundle labels = UserTestTool.labels;
    protected static PersistentProperties props = UserTestTool.props;
    
    private DocumentInfo   documentInfo;
    private String         file;
    private Properties     formParameter;
    private HttpRequest    request;
    private HttpResponse   response;
    private String         id;            // userid as string
    private long           userId;        // userid as integer
    private String         nodeId = ""; // NodeId of the current object.
    private long           start = 0L; // Start time of visit to page
    private String         frame = ""; // Name of this frame
    private String         parentNodeId = ""; // nodeId of parent frame
    private String         parentFrame = ""; // Name of parent frame
    private String         referrerNodeId = ""; // NodeId of the referrer

    public UserTestToolMeg(scone.Plugin plugin) {
        this.plugin = plugin;
    }

    public void handleRequest(RequestEvent e) throws RequestRejectedException {

        documentInfo = (DocumentInfo) e.getRequestInfo(); // get RequestInfo
        file = documentInfo.getPath();           // get Path+File of the URL
        formParameter = FormHelper.interpretFormData(e);  // get Query Parameter from URL
        request = new HttpRequest(e, true);          // Get the request header
        id = request.getCookie("ID");          // Get Cookie "ID"
      
        
/*
        if (AccessTracking.props.get("Disable user handling").equals("true")) {
            id = "0";
        }  // User tracking disabled: UserID is always "0"

        // test if the cookie contains a valid UserID
        try {
            if (id != null) {
                userId = Long.parseLong(id);
            }
        } catch (NumberFormatException ex) {
            System.err.println("Error: Cookie ID is no number");
            userId = 0L;
            id = null;
        }
*/

        HttpGenerator g = null;


        if (file.startsWith("/blank")) {
			StaticHtmlGenerator sg = new StaticHtmlGenerator(); // Return generated document to the client
			String htmlCode = "<html><body></body></html>\n";   
            if (utc != null) {
                utc.pageCalled(file);
            }
			sg.setStaticHtml(htmlCode);
			sg.setContentType("text/html");      // Set type to javascript
			g = sg;                                               // Return Generator
        }else if (file.startsWith("/testcanceled")) {
			StaticHtmlGenerator sg = new StaticHtmlGenerator(); // Return generated document to the client
			String htmlCode = "<html><body><h2>"+labels.getString("cancelled1")+"</h2>"+labels.getString("cancelled2")+" <a href=\"javaScript: self.close()\">"+labels.getString("cancelled3")+"</a>\n";
			htmlCode += "<p>"+labels.getString("cancelled4")+" <a href=\"http://usertest.scone.de\">"+labels.getString("cancelled5")+"</a></p></body></html>\n";  
            if (utc != null) {
                utc.pageCalled(file);
            }
			sg.setStaticHtml(htmlCode);
			sg.setContentType("text/html");      // Set type to javascript
			g = sg;                                               // Return Generator
        }else if (file.startsWith("/testended")) {
			StaticHtmlGenerator sg = new StaticHtmlGenerator(); // Return generated document to the client
			String htmlCode = "<html><body><h2>"+labels.getString("testend1")+"</h2>"+labels.getString("testend2")+" <a href=\"javaScript: self.close()\">"+labels.getString("testend3")+"</a>\n";
			htmlCode += "<p>"+labels.getString("testend4")+" <a href=\"http://usertest.scone.de\">"+labels.getString("testend5")+"</a></p></body></html>\n";  
            if (utc != null) {
                utc.pageCalled(file);
            }
			sg.setStaticHtml(htmlCode);
			sg.setContentType("text/html");      // Set type to javascript
			g = sg;                                               // Return Generator
		} else {
			StaticHtmlGenerator sg = new StaticHtmlGenerator(); // Return generated document to the client
			String htmlCode = "<html><body>";
            htmlCode +=	"\n<script type='text/javascript'>\n<!--\nfunction resizeBrowser() {\nwindow.resizeTo(screen.width/2,screen.height-32);\nwindow.moveTo(screen.width/2,0);\n}\n//-->\n</script>\n";
			htmlCode += "<h2>"+labels.getString("teststart1")+"</h2>"+labels.getString("teststart2")+"<br>";
			htmlCode += "<p style=\"text-align:left; margin-left:1.4cm; margin-right:1.4cm\">"+labels.getString("teststart3")+" ";
			htmlCode += "<a href=\"javascript:resizeBrowser()\" title=\""+labels.getString("teststart4")+"\">"+labels.getString("teststart5")+"</a></p></body></html>\n";   
            if (utc != null) {
                utc.pageCalled(file);
            }
			sg.setStaticHtml(htmlCode);
			sg.setContentType("text/html");      // Set type to javascript
			g = sg;                                               // Return Generator
		}
			
        response = g.getHttpResponse();                   // Get http response header
        // Besser eine Fehlermeldung zurückgeben?
        response.add("Pragma", "no-cache");
        response.add("Cache-control", "no-cache, must-revalidate");
        response.add("Expires", "0");
        // response.setCache(false);

        // Send Response to Browser
        try {
            forwardRequest(g, e);
        } catch (java.io.IOException ex) {
            System.out.println("Error sending response in UserTestToolMeg!");
        }
	}


    /*
     * Create most important mime types from file extensions
     */
    private String getContentType(String ext) {
        ext = ext.toLowerCase();
        if (ext.equals("txt")) {
            return "text/txt";
        }
        if (ext.equals("css")) {
            return "text/css";
        }
        if (ext.equals("js")) {
            return "application/x-javascript";
        }
        if (ext.equals("gif")) {
            return "image/gif";
        }
        if (ext.equals("jpg")) {
            return "image/jpeg";
        }
        return "text/html";
    }

    /*
     * Create nodeId, start and frame from query string
     */
    private void getAccessKey(String filenameStart) {
        // get nodeId from filename. This is not a query parameter, as there are otherwise problems
        // with frames.
        try {
            nodeId = file.substring(filenameStart.length());
            if (nodeId == null || nodeId.length() == 0) {
                nodeId = "0";
            }								// was it available?

            // get start time
            String startString = formParameter.getProperty("start");

            // System.out.println("AccessTrackingMeg: start = " + startString);
            // startString = file.substring(file.indexOf("?start=")+7, file.indexOf("&frame="));
            // System.out.println("AccessTrackingMeg: start = " + startString);
            if (startString == null) {
                startString = "0";
            }
            start = Long.parseLong(startString);			// Convert to long
            // Date startDate = new Date(start); System.out.println(startDate);

            // Name of this frame/window
            frame = formParameter.getProperty("frame");
            if (frame == null) {
                frame = "";
            }
            // System.out.println("frame = " + frame);
        } catch (NumberFormatException ex) {
            System.err.println("AccessTrackingMeg: Error creating numbers: " + file);
            System.err.println("nodeId = " + nodeId);
            System.err.println("start = " + start);
            System.err.println("frame = " + frame);
            nodeId = "0";
            start = 0;
            frame = "";
        }
    }

    /*
     * What is the parent, the frame name, the parent frame name, the referrer etc.
     * This method is called from _start and from _loaded to miminize problems
     * caussed by "§%§%" browser JS-bugs...
     */
    private void getBrowserData() {
        // Parent frame name
        parentFrame = formParameter.getProperty("parent");
        if (parentFrame == null) {
            parentFrame = "";
        }
        // System.out.println("parent = " + parentFrame);

        // int referrer (NodeId: where did the user come from...)
        String referrerUri = formParameter.getProperty("referrer");

        if (referrerUri == null) {
            referrerUri = "";
        } else {
            try {
                NetNode referrerNetNode = NetNodeCache.get(referrerUri);

                referrerNodeId = referrerNetNode.getNodeId();
            } catch (Exception uriException) {
                System.out.println("Exception: referrerUri = " + referrerUri);
                if (referrerUri.equals("[Unknown Origin]")) {
                    referrerNodeId = "Bookmark";
                }  // Bookmark for Netscape ???
                if (referrerUri.equals("[New Window]")) {
                    referrerNodeId = "New Window";
                }      // New window was opened and name was assigned
            }
        }
        // System.out.println("referrerUri = " + referrerUri);
        // System.out.println("referrer Id = " + referrerNodeId);

        // Parent Frame Uri, if available: int parentNodeId
        String parentUri = formParameter.getProperty("parentUri");

        if (parentUri == null) {
            parentUri = "";
        } else {
            NetNode parentNetNode = NetNodeCache.get(parentUri);

            parentNodeId = parentNetNode.getNodeId();
        }
        // System.out.println("parentUri = " + parentUri);
        // System.out.println("parent Id = " + parentNodeId);
    }

    public static void setUtc(UserTestControl AUtc) {
        utc = AUtc;
    }
    

    
}
