/*
 * Scone - The Web Enhancement Framework
 * Copyright (C) 2009 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.robot;


import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import scone.netobjects.SimpleUri;

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.FileGenerator;
import com.ibm.wbi.protocol.http.beans.FormHelper;
import com.ibm.wbi.protocol.http.beans.StaticHtmlGenerator;


/**
 * This HttpGenerator generates a web-interface for the robot.
 *
 * @author Frank Wollenweber
 */




class RobotMonitorMeg extends HttpGenerator {

    public class SimpleRobotUser implements RobotUser {

        public void robotNewPage(RobotHtmlNode robotHtmlNode, RobotTask robotTask) {}

        public void robotTaskFinished(RobotTask robotTask) {
            System.out.println("");
            System.out.println("RobotTask " + robotTask.getStartURI().toString() + " finished");
            long time = Math.round((robotTask.getEndTime() - robotTask.getStartTime()) / 1000);

            System.out.println("Time : " + time + " seconds");
            System.out.println("Checked URL: " + robotTask.getCheckedUris());
            System.out.println("Filtered URLS " + robotTask.getFilteredUris());
            System.out.println("Queued URL: " + robotTask.getQueuedUris());
            System.out.println("Cache Hits: " + robotTask.getCacheHits());
            System.out.println("Downloaded URLs: " + robotTask.getDownloadedUris());
            System.out.println("");
        }
    }

    private DocumentInfo documentInfo;
    private String file;
    private Properties formParameter;
    private HttpRequest request;
    private HttpResponse response;
    private String id;
    private long userId = 0L;
    private Robot robot;

    private StaticHtmlGenerator listRobotTasks() {
        StaticHtmlGenerator sg = new StaticHtmlGenerator(); // Return generated document to the client
        String htmlCode;

        htmlCode = "<HTML>\n<HEAD>\n<TITLE>Scone Robot-Monitor</TITLE>\n</HEAD>\n<BODY>\n";
        htmlCode += "<img src=\"http://_robot.scone.de/scone.jpg\"><BR>\n";
        htmlCode += "<H2><I>Scone Robot-Monitor</I></H2>\n";
        htmlCode += "<P><b>Tasks: " + robot.getNumberOfRobotTasks()
                + "<br>Jobs in PageLoaderpool: "
                + robot.getJobsInPageLoaderPool() + "</b></P>\n";
        htmlCode += "<TABLE border=1 cellpadding=1 cellspacing=0>\n";
        htmlCode += "<TR><TH align=left>Task</TH><TH align=left>Depth</TH><TH align=left>Queue-Lenght</TH><TH align=left>Open URLs</TH><TH align=left>Found Pages</TH><TH>&nbsp;</TH></TR>\n";
        Vector robotTasks = robot.getRobotTasks();
        Enumeration tasks = robotTasks.elements();

        while (tasks.hasMoreElements()) {
            RobotTask rt = (RobotTask) tasks.nextElement();
            Enumeration openUrisEnum = rt.getOpenUris();
            String openUrisString = "";

            while (openUrisEnum.hasMoreElements()) {
                QueueEntry qe = (QueueEntry) openUrisEnum.nextElement();
                SimpleUri suri = qe.getURI();

                openUrisString += suri.toString() + "<br>";
            }
            htmlCode += "<TR><TD>" + rt.getStartURI().toString() + "</TD><TD>"
                    + rt.getDepth() + "</TD><TD>"
                    + robot.getNumberOfPendingQueueEntries(rt) + "</TD><TD>"
                    + openUrisString + rt.getNumberOfOpenUris() + "</TD><TD>"
                    + rt.getNumberOfResultNodes()
                    + "<TD><a href=\"http://_robot.scone.de/_stopTask?task_id="
                    + rt.getId() + "\">stop</a></TD></TR>\n";
        }
        htmlCode += "</TABLE><BR>\n";
        htmlCode += "<P><A href=\"http://_robot.scone.de\"><B>Refresh</B></A></P>\n";
        htmlCode += "<H3>Create new RobotTask</H3>";
        htmlCode += "<FORM method=\"get\" action=\"http://_robot.scone.de/_newTask\">";
        htmlCode += "<TABLE border=\"0\">";
        htmlCode += "<TR><TD>Start URL:</TD><TD><INPUT type=\"text\" name=\"url\" size=\"50\"></TD></TR>";
        htmlCode += "<TR><TD>Crawl depth:</TD><TD><INPUT type=\"text\" name=\"depth\" size=\"2\" value=\"2\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; or download only HEAD: <input type=\"checkbox\" name=\"headonly\" value=\"1\"></TD></TR>";
        htmlCode += "<TR><TD valign=\"top\">Crawl restriction:</TD><TD>";
        htmlCode += "<INPUT type=\"radio\" name=\"restriction\" value=\"no\">No restriction<BR>";
        htmlCode += "<INPUT type=\"radio\" name=\"restriction\" value=\"internal\" checked>Only internal links<BR>";
        htmlCode += "<INPUT type=\"radio\" name=\"restriction\" value=\"subdirectories\">Only sub directories<BR>";
        htmlCode += "<INPUT type=\"radio\" name=\"restriction\" value=\"external\">Only external links<BR>";
        htmlCode += "</TD></TR>";
        htmlCode += "<TR><TD>Max downloaded URLS:</TD><TD><INPUT type=\"text\" name=\"maxdownloadurls\" size=\"10\" value=\"-1\"> (-1 means no limit)</TD></TR>";
        htmlCode += "<TR><TD>Max download time:</TD><TD><INPUT type=\"text\" name=\"maxdownloadtime\" size=\"10\" value=\"30000\"> (-1 means no limit)</TD></TR>";
        htmlCode += "<TR><TD>Max download size:</TD><TD><INPUT type=\"text\" name=\"maxpagesize\" size=\"10\" value=\"50000\"> (-1 means no limit)</TD></TR>";
        htmlCode += "<TR><TD>Check database:</TD><TD><input type=\"checkbox\" name=\"checkdatabase\" value=\"1\" checked></TD></TR>";
        htmlCode += "<TR><TD>Content seen test:</TD><TD><input type=\"checkbox\" name=\"contentseen\" value=\"1\"></TD></TR>";
        htmlCode += "<TR><TD>Update time:</TD><TD><INPUT type=\"text\" name=\"updatetime\" size=\"10\" value=\"1440\"> minutes (-1 means infinite update time)</TD></TR>";
        htmlCode += "</TABLE>";
        htmlCode += "<INPUT type=\"submit\" name=\"submit\" value=\"Start\">";
        htmlCode += "</FORM>";
        htmlCode += "</BODY></HTML>";
        sg.setStaticHtml(htmlCode);
        return sg;
    }

    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
        robot = Robot.instance(); // Get a reference to the scone-robot
        HttpGenerator g = null;

        if (file.equals("/_stopTask")) {
            robot.stopRobotTask(Integer.parseInt(formParameter.getProperty("task_id")));
        } else {
            if (file.equals("/_newTask")) {
                SimpleUri starturi = new SimpleUri(formParameter.getProperty("url"));
                int depth = Integer.parseInt(formParameter.getProperty("depth"));
                String r = formParameter.getProperty("restriction");
                int restriction = RobotTask.ALL;

                if (r.equals("internal")) {
                    restriction = RobotTask.INTERNAL;
                } else {
                    if (r.equals("subdirectories")) {
                        restriction = RobotTask.SUBDIRECTORIES;
                    } else {
                        if (r.equals("external")) {
                            restriction = RobotTask.EXTERNAL;
                        }
                    }
                }
                RobotTask rt = new RobotTask(starturi, depth, restriction, new SimpleRobotUser());
                int maxDownloadUrls = Integer.parseInt(formParameter.getProperty("maxdownloadurls"));

                rt.setMaxDownloadUris(maxDownloadUrls);
                long maxDownloadTime = Long.parseLong(formParameter.getProperty("maxdownloadtime"));

                rt.setMaxDownloadTime(maxDownloadTime);
                int maxPageSize = Integer.parseInt(formParameter.getProperty("maxpagesize"));

                rt.setMaxPageSize(maxPageSize);
                boolean headOnly = (formParameter.getProperty("headonly")
                        != null);

                rt.setHeadOnly(headOnly);
                boolean checkDatabase = (formParameter.getProperty("checkdatabase")
                        != null);

                rt.setCheckDatabase(checkDatabase);
                if (formParameter.getProperty("contentseen") != null) {
                    rt.setDoContentSeenTest();
                }
                long updateTime = Long.parseLong(formParameter.getProperty("updatetime"));

                updateTime = updateTime * 60000;
                Date updateDate = new Date();

                rt.setUpdateDate(updateDate.getTime() - updateTime);
                robot.scan(rt);
            } else {
                if (file.length() > 1) {

                    // Create response from file

                    // System.out.println("Returning: "+file);
                    String ext = file.substring(file.lastIndexOf(".") + 1);

                    // System.out.println(getContentType(ext));
                    FileGenerator rg = new FileGenerator("resources/scone/proxy" + file, getContentType(ext));

                    g = rg;
                }
            }
        }

        // If not a filename, return ROBOT-Screen with tasklist.
        if (g == null) {
            g = listRobotTasks();
        }
        response = g.getHttpResponse(); // Get http response header
        response.setCache(false);

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

    /*
     * 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";
    }
}
