/* $Id: LoggerMinerServlet.java,v 1.1 2002/06/27 18:13:47 em Exp $
 */

import java.io.* ;
import java.net.* ;
import java.util.* ;
import java.text.* ;
import java.lang.String;

import javax.servlet.*;
import javax.servlet.http.*;

import com.hp.hpl.jena.util.* ;

import com.hp.hpl.mesa.rdf.jena.model.* ;
import com.hp.hpl.mesa.rdf.jena.common.* ;
import com.hp.hpl.mesa.rdf.jena.mem.ModelMem;

import com.hp.hpl.mesa.rdf.jena.vocabulary.RDF;
import com.hp.hpl.mesa.rdf.jena.vocabulary.RDFS;

import vocabulary.DC;
import vocabulary.W3S;
import vocabulary.CYC;
import vocabulary.FOAF;

/** Mine IRC logs (Action Items and potential other useful bits of
 *  information) from RRSAgent (Logger) logs
 *
 *  Usage: --data URL --verbose --quiet
 *     --data URL           Data source : URL or filename"
 *     --verbose            Verbose - more messages
 *     --quiet              Quiet - less messages
 *
 *  note: for merging purporses, this application incorporates
 *  ("Accept", "text/xml") http access so --date URL's should not have
 *  extensions
 * 
 * author - Eric Miller
 * version - $Id: LoggerMinerServlet.java,v 1.1 2002/06/27 18:13:47 em Exp $
 */


public class LoggerMinerServlet extends HttpServlet {

    static PrintWriter out = null;
    public static String ircurl = "";

    public void init(ServletConfig config) throws ServletException {

    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws IOException, ServletException  {
	
	// get output

        out = response.getWriter();

	ircurl = request.getParameter("uri");

	if ((ircurl == null) || (ircurl == "")) {

	    response.setContentType("text/html");

	    printForm();

	} else {

	    Model model = new ModelMem();

	    try {
		
		response.setContentType("text/xml");

		URL url = new URL (ircurl);
		     
		URLConnection connection = url.openConnection();

		connection.setRequestProperty("Accept", "text/xml");

		// String userpassEncoded = auth.substring(6);
		// connection.setRequestProperty("Authorization", "Basic " + userpassEncoded);
		// connection.setRequestProperty("Proxy-Authorization", userpassEncoded);
		     
		InputStream content = (InputStream) connection.getInputStream();
		
		BufferedReader in = new BufferedReader (new InputStreamReader (content));
		
		// get a Reader from a BufferedReader...
		
		Reader reader = (Reader) in;
		
		model.read(reader, ircurl, null);

		mineLog(model);

		
	    } catch (Exception e) {
		out.println(e);
	    }
	    
	}
	out.close();
    }


    public void doPost(HttpServletRequest request,
		       HttpServletResponse response) throws IOException, ServletException {
	
        doGet(request, response);
    }
    

    static public void printForm() {

	out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
	out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
	out.println("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
        
        out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        out.println("<head>");
        out.println("<title>SWAMT LoggerMiner Service</title>");
        out.println("</head>");

        out.println("<body>");
        out.println("<h1>SWAMT LoggerMiner Service</h1>");

	out.println("<form action=\"/2001/06/swamt/services/loggerminer/\"  method=\"get\">");

	out.println("<br />");
	out.println("<input type=\"text\" size=\"50\" name=\"uri\" maxlength=\"800\" value=\"\" />");
	out.println("<input type=\"submit\" value=\"Mine IRC log\"/>");
	out.println("<br />");

        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
    }


    static public void mineLog(Model model) throws RDFException {

	String atext = null;
	String atitle = null;
	String agentName = null;
	String name = null;

	Resource irclog = null;
	Resource agent = null;
	Resource iresource = null;
	Resource aresource = null;


	// check to see if we've got the neccessary stuff

	if (model == null) return;

	printHeader();

	// select all the resources with a FOAF.chatEventList property

	ResIterator iter = model.listSubjectsWithProperty(FOAF.chatEventList);

	if (iter.hasNext()) {

	    while (iter.hasNext()) {

		irclog = iter.next();

		// ok, loop through eventlist and mine log for ...

		// Actions

		// get seq of chat events
		
		Seq items = irclog.getProperty(FOAF.chatEventList).getSeq();
		
		for (int ai = 1; (ai <= items.size()); ai++) {
		    
		    iresource = items.getResource(ai);
		    
		    if (iresource.hasProperty(DC.relation)) {
			
			aresource = (Resource) iresource.getProperty(DC.relation).getObject();
			
			if (aresource.hasProperty(DC.description)) {

			    // get trimmed title

			    atext = aresource.getProperty(DC.description).getString().trim();

			    if (atext.startsWith("ACTION: ")) {

				atitle = atext;			    

				render("<w3s:ActionItem rdf:about=\"" + iresource.toString() + "\">\n");
				// render("  <cyc:subEvents rdf:resource=\"" + irclog.toString() + "\" />\n");
				render("  <dc:source rdf:resource=\"" + aresource.toString() + "\" />\n");

				// see if we can extract an owner of this action item

				int beginidx = atext.indexOf(" ");
				int endidx = atext.indexOf(",");

				beginidx = beginidx + 1;	// skip space
				int length = endidx - beginidx;
				
				String owner = null;
				owner = String.copyValueOf(atext.toCharArray(), beginidx, length);			       
				
				if (owner != null) {
				    // build smart action item

				    render("  <cyc:Agent><cyc:nameOfAgent>" + owner + "</cyc:nameOfAgent></cyc:Agent>\n");

				    // ok, at this point we know we've
				    // got an Action item and an
				    // owner... trip action title
				    // accordingly
				    
				    endidx = endidx + 1; // skip comma

				    atitle = String.copyValueOf(atext.toCharArray(), endidx, atext.length() - endidx).trim();
				}

				
				render("  <dc:title>" + atitle + "</dc:title>\n");
				render("</w3s:ActionItem>\n\n");

			    }
			}

		    } else {

			// ok... its a simple event; let's test to see
			// if someone joined the call

			if (iresource.hasProperty(DC.description)) {

			    // get trimmed description

			    atext = iresource.getProperty(DC.description).getString().trim();

			    if (atext.startsWith("+")) {

				if (iresource.hasProperty(DC.creator)) {
				    
				    agent = (Resource) iresource.getProperty(DC.creator).getObject();
				    
				    if (agent.hasProperty(FOAF.nick)) {
					
					agentName = agent.getProperty(FOAF.nick).getString();

					if ((agentName != null) && (agentName.equals("Zakim"))) {
					    
					    // we have a person joining the call
					    
					    name = String.copyValueOf(atext.toCharArray(), 1, atext.length() - 1).trim();
					    
					    render("<rdf:Description rdf:about=\"" + irclog.toString() + "\">\n");
					    render("  <cyc:groupMember>\n");
					    render("    <cyc:Agent><cyc:agentName>" + name + "</cyc:agentName></cyc:Agent>\n");
					    render("  </cyc:groupMember>\n");
					    render("</rdf:Description>\n\n");
					}
				    }
				}
			    }
			}
		    }
		}
	    }
	}

	// end

	printFooter();
    }


    public static void render (String outputString) {

	if ((outputString != null) & (outputString != "")) {
	    out.print(outputString);
	}

    }

    public static void printHeader() {
	
	render("<?xml version='1.0'?>\n\n");

	render("<!-- RDF/XML extracted from IRC LOG: '" + ircurl + "'\n");
	render("     by $Id: LoggerMinerServlet.java,v 1.1 2002/06/27 18:13:47 em Exp $ -->\n\n");


	render("<rdf:RDF \n");
	render("  xmlns:cyc=\"http://opencyc.sourceforge.net/daml/cyc.daml#\"\n");
	render("  xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
	render("  xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n");
	render("  xmlns:w3s=\"http://www.w3.org/2000/11/mr76/w3cStyle#\">\n\n");

    }

    public static void printFooter() {

	render("</rdf:RDF>\n");
    }


}
