/* ======================================================================
The Bodington System Software License, Version 1.0
  
Copyright (c) 2001 The University of Leeds.  All rights reserved.
  
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1.  Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2.  Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3.  The end-user documentation included with the redistribution, if any,
must include the following acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.

4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.

5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES 
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO 
EVENT SHALL THE UNIVERSITY OF LEEDS OR ITS CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
=========================================================

This software was originally created by the University of Leeds and may contain voluntary 
contributions from others.  For more information on the Bodington Open Source Project, please 
see http://bodington.org/

====================================================================== */

package org.bodington.servlet.facilities;

import java.util.logging.*;


import org.bodington.servlet.*;
import java.sql.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;


// javamail
// /*
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
// javamail
// */

import org.bodington.server.*;
import org.bodington.server.events.*;
import org.bodington.server.realm.User;
import org.bodington.server.realm.UserDetail;
import org.bodington.server.resources.*;
import org.bodington.database.PrimaryKey;
import org.bodington.server.events.Event;
import org.bodington.util.DateFormatter;


public class NotificationFacility extends org.bodington.servlet.facilities.Facility
	{
	

	public String defaultIcon()
		{
		return "binoc.gif";
		}
	public String defaultSmallIcon()
		{
		return "document-small.gif";
		}

    /**
     * Facility subclasses can refuse copying of resources.
     * @return True if resources that use this facility can be copied.
     */
    public boolean canCopy( Resource resource )
    {
        return true;
    }
    
	public void insert( Request req, PrintWriter out, String command, String insertname )
		throws ServletException, IOException
		{
		Logger.getLogger("org.bodington").fine( Thread.currentThread().getName() + " NotificationFacility insert()" );

		if ( command.equalsIgnoreCase( "notifications" ) )
			{
			notifications( req, out );
			return;
			}

		if ( command.equalsIgnoreCase( "resetnotification" ) )
			{
			reset( req, out );
			return;
			}

		if ( command.equalsIgnoreCase( "emailnow" ) )
			{
			if ( out!=null )
			    {
			    out.println( "<p>Email now option no longer implemented. Each user starts their own job.</p>" );
			    }
			return;
			}
			
		if ( command.equalsIgnoreCase( "option" ) )
			{
			option( req, out, insertname );
			return;
			}

		if ( command.equalsIgnoreCase( "confirmoptions" ) )
			{
			confirmoptions( req, out );
			return;
			}

		if ( command.equalsIgnoreCase( "lastemailreport" ) )
			{
			lastemailreport( req, out );
			return;
			}
		
		if ( command.equalsIgnoreCase( "emailsummary" ) )
			{
			emailsummary( req, out );
			return;
			}
		
		super.insert( req, out, command, insertname );
		}

	private void notifications( Request req, PrintWriter out )
		throws IOException
		{
		int location, e, n;
		Resource res;
		

		org.bodington.servlet.HttpSession http_session;
		NavigationSession nav_session;
		User user;
		UserEventSetup ues=null;
		
		try
		{
		//http_session = (org.bodington.servlet.HttpSession)req.getSession( false );
		nav_session = req.getServerNavigationSession();
		if ( !nav_session.isAuthenticated() || nav_session.isAnonymous() )
			{
			out.println( "<HR>You are not checked in and so notifications are not available." );
			return;
			}
		user = nav_session.getAuthenticatedUser();
		
        	ues = UserEventSetup.findUserEventSetup( "user_id = " + user.getUserId() );
        	if ( ues == null )
        		{
        		ues = new UserEventSetup();
        		ues.setUser( user );
        		ues.save();
        		}
			
			Calendar lastmonth, since;
			since=Calendar.getInstance();
			since.setTime( ues.getCutoffTime() );
			lastmonth=Calendar.getInstance();
			lastmonth.setTime( new java.util.Date( System.currentTimeMillis() ) );
			lastmonth.add( Calendar.MONTH, -1 );
			if ( since.before( lastmonth ) )
				{
				ues.setCutoffTime( new java.sql.Timestamp( lastmonth.getTime().getTime() ) );
				ues.save();
				}
			}
		catch ( Exception ex )
			{
			out.println( "<HR>There was a technical problem trying to get your notification settings.<HR>" + ex.getMessage() );
			return;
			}

		n=0;
		try
			{
            Enumeration enum2;
            Enumeration enum = ues.findResources();
            Event event;
            PrintWriter writer = new PrintWriter( out );
            for ( location=0; enum!=null && enum.hasMoreElements(); location++ )
            	{
            	res = (Resource) enum.nextElement();
            
            	enum2 = ues.findEventsForResource( res );
            	for ( e=0; enum2.hasMoreElements(); )
            		{
            		event = (Event)enum2.nextElement();
            		if ( !event.checkPermission() )
            			continue;
            		
            		if ( e==0 )
            			{
						out.print( "<TABLE CLASS=bs-table-opaque><TR><TD COLSPAN=2 CLASS=bs-cell-special>" );
		            	out.print( "<H4>Events at: <A TARGET=_top HREF=" );
				out.print( req.getContextPath() );
		            	out.print( req.getServletPath() );
		            	out.print( res.getFullName() );
		            	out.print( ">" );
		            	out.print( res.getTitle() );
		            	out.println( "</A></H4></TD></TR>" );
		            	}
	            	out.println( "<TR><TD valign=top>" );
	            	DateFormatter.outputDate( out, event.getEventTime(), 2 );
	            	out.println( "</TD><TD valign=top >" );
            		event.printMessage( writer, true );
            		writer.flush();
	            	out.println( "</TD></TR>" );
	            	e++;
            		n++;
            		}
            	if ( e>0 )
            		out.println( "</TABLE><BR><BR>" );
            	}
            if ( location==0 )
				{
				out.println( "<HR><P>You have no locations set for notification</P>" );
				return;
				}
			}
		catch ( Exception ex )
			{
			out.println( "<HR>There was a technical problem trying to get a list of events.<HR>" + ex.getMessage() );
			return;
			}


		
		if ( n==0 )
			{
			out.println( "<HR>No events occured in any locations on your notification list since "  );
			DateFormatter.outputDate( out, ues.getCutoffTime(), 0 );
			}

		}

	
	
	private void reset( Request req, PrintWriter out )
		throws IOException
		{

		String reset = req.getParameter( "reset" );
		if ( reset==null ) return;
		if ( reset.length()==0 ) return;

		org.bodington.servlet.HttpSession http_session;
		NavigationSession nav_session;
		User user;
		UserEventSetup ues=null;
		
		try
		{
		//http_session = (org.bodington.servlet.HttpSession)req.getSession( false );
		nav_session = req.getServerNavigationSession();
		if ( !nav_session.isAuthenticated() || nav_session.isAnonymous() )
			{
			out.println( "<HR>You are not checked in and so notifications are not available." );
			return;
			}
		user = nav_session.getAuthenticatedUser();
        	ues = UserEventSetup.findUserEventSetup( "user_id = " + user.getUserId() );
        	if ( ues == null )
        		{
        		ues = new UserEventSetup();
        		ues.setUser( user );
        		}

       		ues.setCutoffTime( new java.sql.Timestamp( System.currentTimeMillis() ) );
			ues.save();
			
			out.println( "<HR>Confirmation - only events after " );
			out.println( ues.getCutoffTime().toString() );
			out.println( " will be reported. " );
			}
		catch ( Exception ex )
			{
			out.println( "<HR>There was a technical problem trying to get your notification settings.<HR>" + ex.getMessage() );
			return;
			}

		}

	
	
    private void schedule( Request req, PrintWriter out )
	throws IOException
	{
	BuildingContext context=BuildingContext.getContext();
	User user = (User)context.getUser();
	try
	    {   
	    Job job = Job.findJob( 
			    "user_id = " + user.getUserId() + 
			    " AND session_name = 'org.bodington.server.events.EventMailer' " +
			    " AND method_name = 'sendEventMail'" );

	    if ( job == null )
		{
		out.print( "No schedule for sending Emails." );
		}
	    else
		{
		out.print( job.getScheduleDescription() );
		}
	    }
	catch ( BuildingServerException bsex )
	    {
	    out.print( "Unable to display schedule." );
	    }
	}
	    
    private void option( Request req, PrintWriter out, String opt )
	throws IOException
	{
		org.bodington.servlet.HttpSession http_session;
		NavigationSession nav_session;
		User user;
		UserEventSetup ues=null;
	UserDetail ud = null;
	String address=null;
		
		try
		{
		//http_session = (org.bodington.servlet.HttpSession)req.getSession( false );
		nav_session = req.getServerNavigationSession();
		if ( !nav_session.isAuthenticated() || nav_session.isAnonymous() )
			{
			out.println( "<HR>You are not checked in and so notifications are not available." );
			return;
			}
		user = nav_session.getAuthenticatedUser();

	//TimeZone tz=TimeZone.getDefault();
	//SimpleDateFormat sdf= new SimpleDateFormat();


	    ues = UserEventSetup.findUserEventSetup( "user_id = " + user.getUserId() );
	if ( ues == null )
		{
		ues = new UserEventSetup();
		ues.setUser( user );
		ues.save();
		}


	ud = UserDetail.findUserDetail( "user_id = " + user.getUserId() );
	if ( ud!=null )
		address = ud.getEMailAddress();
		}
	catch ( Exception ex )
		{
		out.println( "<HR>There was a technical problem trying to get your notification settings.<HR>" + ex.getMessage() );
		return;
		}

    if ( opt.equalsIgnoreCase( "frequency" ) )
	{
	out.print( "<INPUT TYPE=RADIO NAME=frequency VALUE=0 " );
	out.println( "> Never send me Email notifications.<BR>" );
	out.print( "<INPUT TYPE=RADIO NAME=frequency VALUE=7 " );
	out.println( "> Send me Email notifications no more than once a week.<BR>" );
	out.print( "<INPUT TYPE=RADIO NAME=frequency VALUE=1 " );
	out.println( "> Send me Email notifications no more than once a day.<BR>" );
	}

    if ( opt.equalsIgnoreCase( "address" ) )
	{
	out.println( "<INPUT NAME=address VALUE=\"" +
			(address==null?"":address) +
			"\">" );
	}
    }



	private void confirmoptions( Request req, PrintWriter out )
		throws IOException
		{
		String sql, str, frq, address;
		int i, j;
		UserEventSetup ues;
		UserDetail ud;
		org.bodington.servlet.HttpSession http_session;
		NavigationSession nav_session;
		User user;

		try
			{
		//http_session = (org.bodington.servlet.HttpSession)req.getSession( false );
		nav_session = req.getServerNavigationSession();
		if ( !nav_session.isAuthenticated() || nav_session.isAnonymous() )
			{
			out.println( "<HR>You are not checked in and so notifications are not available." );
			return;
			}
		user = nav_session.getAuthenticatedUser();

		str=req.getParameter( "options" );
		if ( str==null )
			return;

		frq=req.getParameter( "frequency" );
		if ( frq==null            || 
		    !(frq.equals("0")|| 
		      frq.equals("1")||
		      frq.equals("7")   )    )
		    {
		    out.println( "Technical problem: invalid form input." );
		    return;
		    }
		address=req.getParameter( "address" );
		if ( address==null )
		    {
		    out.println( "Technical problem: invalid form input." );
		    return;
		    }

        if ( !frq.equals( "0" ) )
            {
            if ( address.indexOf( '@' ) < 1 )
                {
                out.println( "The Email address must contain an '@' symbol." );
                return;
                }
            }



        	ues = UserEventSetup.findUserEventSetup( "user_id = " + user.getUserId() );
        	if ( ues == null )
        		{
        		ues = new UserEventSetup();
        		ues.setUser( user );
        		ues.save();
        		}
        		
			if ( frq.equals( "7" ) )
			    {
			    ues.setEMailCutoffTime( 
    					new java.sql.Timestamp( System.currentTimeMillis()-(7*24*60*60*1000) ) );
			    }
			if ( frq.equals( "1" ) )
			    {
			    ues.setEMailCutoffTime( 
    					new java.sql.Timestamp( System.currentTimeMillis()-(24*60*60*1000) ) );
			    }
		ues.setEMailFrequency(Integer.parseInt(frq));
        	ues.save();
        	
        	ud = UserDetail.findUserDetail( "user_id = " + user.getUserId() );
        	if ( ud==null )
        		{
        		ud=new UserDetail();
        		ud.setUser( user );
        		}
       		ud.setEMailAddress( address );
       		ud.save();
       		
		JobScheduler scheduler = JobScheduler.getJobScheduler( false );
       		Job job = Job.findJob( 
       				"user_id = " + user.getUserId() + 
       				" AND session_name = 'org.bodington.server.events.EventMailer' " +
       				" AND method_name = 'sendEventMail'" );
       				
       		if ( job != null )
		    scheduler.deleteJob( job );
		
		if ( scheduler==null )
		    throw new Exception( "Unable to schedule a job to send Email notification." );
		if ( frq.equals( "1" ) )
		    scheduler.addJob( "org.bodington.server.events.EventMailer", "sendEventMail", "", Job.REPEAT_TYPE_DAILY );
		else if ( frq.equals( "7" ) )
		    scheduler.addJob( "org.bodington.server.events.EventMailer", "sendEventMail", "", Job.REPEAT_TYPE_WEEKLY );
		else
		    scheduler.addJob( "org.bodington.server.events.EventMailer", "sendEventMail", "", Job.REPEAT_TYPE_NEVER );
       				
		}
		catch ( Exception ex )
			{
			logException( out, "NotificationFacility", "insert", 
			    "There was a technical problem trying to set your notification settings.",
			    ex );
			return;
			}

		}

	private void lastemailreport( Request req, PrintWriter out )
	    throws IOException
	    {
	    String sql, str, frq, address;
	    int i, j;

		org.bodington.servlet.HttpSession http_session;
		NavigationSession nav_session;
		User user;

		try
			{
		//http_session = (org.bodington.servlet.HttpSession)req.getSession( false );
		nav_session = req.getServerNavigationSession();
		if ( !nav_session.isAuthenticated() || nav_session.isAnonymous() )
			{
			out.println( "<HR>You are not checked in and so notifications are not available." );
			return;
			}
		user = nav_session.getAuthenticatedUser();

		Job job = Job.findJob( 
		"user_id = " + user.getUserId() + 
		" AND session_name = 'org.bodington.server.events.EventMailer' " +
		" AND method_name = 'sendEventMail'" );

		if ( job == null )
		    return;

		// find the most recent JobResult
		JobResult job_result = JobResult.findJobResult( 
			    "job_id = " + job.getJobId().toString() + 
			    " AND execution_time IN " + 
			    "(SELECT max(execution_time) FROM job_results WHERE job_id = " + 
				job.getJobId().toString() + ")" );
		
		if ( job_result == null )
		    return;
		
		out.println( "<H4>Last Result of Scheduled Job to Send Email</H4>" );
		out.println( "<table align=\"center\" class=\"bs-table-opaque\"><tr><td class=\"bs-cell-special\">" );
		out.println( "<em>Execution Time</em></td></tr>" );
		out.println( "<tr><td>" );
	        DateFormatter.outputDate( out, job_result.getExecutionTime(), 2 );
		out.println( "</td></tr>" );
		out.println( "<tr><td class=bs-cell-special><em>Status</em></td></tr>" );
		out.println( "<tr><td>" );
		switch ( job_result.getResultCode() )
		    {
		    case JobResult.RESULT_INCOMPLETE:
			out.println( "Email notification currently being processed." );
			break;
		    case JobResult.RESULT_OK:
			out.println( "Email notification update ran OK." );
			break;
		    case JobResult.RESULT_ERROR:
			out.println( "Email notification update failed." );
			break;
		    }
		out.println( "<tr><td class=bs-cell-special><em>Report</em></td></tr>" );
		out.println( "<tr><td><pre>" );
		out.println( job_result.getString() );
		out.println( "</td></tr></pre></table>" );
		}
	    catch ( Exception ex )
		{
		out.println( "<HR>There was a technical problem trying to set your notification settings.<HR>" + ex.getMessage() );
		return;
		}

	    }

	private void emailsummary( Request req, PrintWriter out )
	    throws IOException
	    {
	    String sql, str, frq, address;
	    int i, j;

		org.bodington.servlet.HttpSession http_session;
		NavigationSession nav_session;
		User user;

		try
			{
		//http_session = (org.bodington.servlet.HttpSession)req.getSession( false );
		nav_session = req.getServerNavigationSession();
		if ( !nav_session.isAuthenticated() || nav_session.isAnonymous() )
			{
			out.println( "<HR>You are not checked in and so notifications are not available." );
			return;
			}
		user = nav_session.getAuthenticatedUser();

		Job job = Job.findJob( 
		"user_id = " + user.getUserId() + 
		" AND session_name = 'org.bodington.server.events.EventMailer' " +
		" AND method_name = 'sendEventMail'" );

		if ( job == null )
		    {
		    out.println( "<p>No Emails will be sent.</p>" );
		    return;
		    }

        	UserDetail ud = UserDetail.findUserDetail( "user_id = " + user.getUserId() );
        	if ( ud==null )
		    {
		    out.println( "<p>No Emails will be sent.</p>" );
		    return;
		    }

		if ( job.getState() == Job.STATE_OVERDUE || job.getState() == Job.STATE_WAITING || job.getState() == Job.STATE_EXECUTING )
		    {
		    out.println( "<p>Email notifications are scheduled to be sent to " );
		    out.println( ud.getEMailAddress() );
		    out.println( ". The schedule is " );
		    out.println( job.getScheduleDescription() );
		    out.println( ".</p>" );
		    return;
		    }
		
		if ( job.getState() == Job.STATE_FAILED )
		    {
		    out.println( "<p>Email notifications are stopped because that last attempt to send Email failed. " );
		    out.println( "Reset the schedule using the form if you want to retry.</p>" );
		    return;
		    }

		out.println( "<p>No Emails will be sent.</p>" );
		return;
		}
	    catch ( Exception ex )
		{
		out.println( "<HR>There was a technical problem trying to set your notification settings.<HR>" + ex.getMessage() );
		return;
		}

	    }


// javamail
/*
	//musn't allow this to run in two threads at the same time.
	private synchronized void emailnow( Request req, PrintWriter out )
		throws IOException
		{
		Vector users= new Vector();
		EventUser eu;
		String sql;
		CharArrayWriter buffer=new CharArrayWriter();

		Calendar calendar = Calendar.getInstance();
		calendar.setTime( new java.util.Date() );
		calendar.add( Calendar.DATE, -1 );
		java.sql.Timestamp since=new java.sql.Timestamp( calendar.getTime().getTime() );
		calendar.setTime( new java.util.Date() );
		calendar.add( Calendar.DATE, -7 );
		java.sql.Timestamp weeksince=new java.sql.Timestamp( calendar.getTime().getTime() );

		Enumeration enum;
		UserEventSetup ues;
		UserDetail ud;
		try
			{
			enum = UserEventSetup.findUserEventSetups( 
					"( email_frequency = 1 AND (email_cutoff_time < '" + since     + " ) )" +
				" OR ( email_frequency = 7 AND (email_cutoff_time < '" + weeksince + " ) )"      );
			
			while ( enum.hasMoreElements() )
				{
				ues = (UserEventSetup)enum.nextElement();
				ud = UserDetail.findUserDetail( "user_id = " ues.getUserId() );
				if ( ud==null || ud.getEMailAddress()==null )
					continue;
					
				buffer.reset();
				PrintWriter writer= new PrintWriter( buffer );

				out.println( eu.toString() );
				writer.println( "Automated Email for " + eu.name + ".");
				writer.println( "This is a personal notification message that lists " );
				writer.println( "events that have occured in locations in the  " );
				writer.println( "Nathan Bodington building since the last notification " );
				writer.println( "message.  To change notification options visit : " );
				writer.println( "http://www.tlsu.leeds.ac.uk/nbodington/ground/reception/notification/" );
				writer.println( "If this message has been sent to your address in error " );
				writer.println( "and the name above is not your name please reply to this Email. " );
				int oldsize=buffer.size();
				usermessage( req, writer, con, eu, since );

				out.println( "<HR>Mailing " + eu.user_id + "?<PRE>" );
				if ( buffer.size() > oldsize )
					{
					out.println( buffer.toString() );
					sendemail( req, buffer, eu );
    				eu.mail_since=new java.sql.Timestamp( new java.util.Date().getTime() );
	    			eu.update(con);
					}
				else
					out.println( "No Email sent." );
				out.println( "</PRE>" );
				}
			}
		catch ( Exception ex )
			{
			out.println( "<HR>There was a technical problem trying to get a list of locations.<HR>" + ex.getMessage() );
			return;
			}

		}

	private synchronized void usermessage( Request req, PrintWriter out, Connection con, EventUser eu, java.sql.Timestamp since )
		throws IOException, SQLException, BuildingException, IllegalAccessException, DBObjectException
		{
		PreparedStatement statement;
		ResultSet results;
		Vector locations;
		UserEventLocation current;
		Event event;
		FacilityList fl;
		Facility facility;
		
		BRealm realm;
		Resource current_resource;
		
		//TimeZone tz=TimeZone.getDefault();
		//SimpleDateFormat sdf= new SimpleDateFormat();
		java.util.Date jdate;
		//String strdate;
		
		String sql;
		int i, j, n=0;

		fl=req.realm.getFacilities();
		if ( fl==null )
			throw new BuildingException( "Technical Problem - can't find facility list." );

		locations=new Vector();
		sql="SELECT * FROM " + DBObject.schema + "user_event_locations WHERE ( user_id = ? AND detail > 0 )";
		Logger.getLogger("org.bodington").fine( sql );
		statement=con.prepareStatement( sql );
		statement.setString( 1, eu.user_id );
		results=statement.executeQuery();
		while ( results.next() )
			{
			current=new UserEventLocation( "", 0, 0 );
			current.load( results );
			locations.addElement( current );
			}

		if ( locations.size()==0 )
			return;

		for ( i=0; i<locations.size(); i++ )
			{
			current=(UserEventLocation)locations.elementAt( i );
			
			try
				{
				current_resource = Resource.findResource( new PrimaryKey( current.location ) );
				
				if ( current_resource==null )
					continue;

				facility=fl.get( new Integer( current_resource.getResourceId().intValue() ) );
				
				if ( eu.mail_since==null )
					sql="SELECT * " +
						"FROM " + DBObject.schema + "events_detail " +
						"WHERE (location = ? AND detail_level <= ? ) " +
						"ORDER BY detail_level ASC, happened DESC";
				else
					sql="SELECT * " +
				    	"FROM " + DBObject.schema + "events_detail " +
						"WHERE (location = ? AND detail_level <= ? AND happened > ? ) " +
						"ORDER BY detail_level ASC, happened DESC";
				
				statement=con.prepareStatement( sql );
				statement.setInt( 1, current.location );
				statement.setInt( 2, current.detail );
				if ( eu.mail_since!=null )
					statement.setString( 3, eu.mail_since.toString() );
				results=statement.executeQuery();
					
				for ( j=0; results.next() && j<10; j++ )
					{
					event=new Event( );
					event.load( results );
					jdate=new java.util.Date( event.happened.getTime() );
					//strdate=sdf.format( jdate );
						
					if ( j==0 )
						{
						int port=req.httpreq.getServerPort();
						out.println( "\n   Location> " + ((current_resource.getTitle()==null)?"no title":current_resource.getTitle() )  );
						out.print(   "Web Address> http://" + req.httpreq.getServerName() );
						if ( port!=80 )
							out.print( ":" + port );
						out.println( req.secureservlet + current_resource.getFullName().substring( 1 ) );
						}
					out.println( "           * " + formatDate( req, jdate, 0 ) );
					out.print(     "             " );
					facility.printEvent( out, event );
					out.println( "" );
					n++;
					}
				if ( j==10 )
					out.println( "There were more events at this location." );
				}
			catch ( Exception ex )
				{
				continue;
				}
			}
		}

	private synchronized void sendemail( Request req, CharArrayWriter buffer, EventUser eu )
		{
		Logger.getLogger("org.bodington").fine( "private synchronized void sendemail( Request req, CharArrayWriter buffer, EventUser eu )" );

		Properties props = new Properties();
		Logger.getLogger("org.bodington").fine( "A" );
	    props.put( "mail.smtp.from", "reception@tlsu.leeds.ac.uk" );
	    props.put( "mail.smtp.user", "reception@tlsu.leeds.ac.uk" );
	    props.put( "mail.smtp.host", "tlsu.leeds.ac.uk" );
		Logger.getLogger("org.bodington").fine( "B" );
		Session session = Session.getDefaultInstance(props, null);
		Logger.getLogger("org.bodington").fine( "C" );

		try
			{
			// create a message
			javax.mail.Message msg = new MimeMessage(session);
		Logger.getLogger("org.bodington").fine( "D" );
			msg.setFrom(new InternetAddress("reception@tlsu.leeds.ac.uk"));
		Logger.getLogger("org.bodington").fine( "E" );
			InternetAddress[] address =
				{new InternetAddress(eu.mail_address)};
		Logger.getLogger("org.bodington").fine( "F" );
			msg.setRecipients(javax.mail.Message.RecipientType.TO, address);
		Logger.getLogger("org.bodington").fine( "G" );
			msg.setSubject( "Nathan Bodington Building Events" );
		Logger.getLogger("org.bodington").fine( "H" );
			msg.setContent( buffer.toString(), "text/plain" );
			//msg.writeTo( System.out );
		Logger.getLogger("org.bodington").fine( "I" );
			javax.mail.Transport.send( msg );
		Logger.getLogger("org.bodington").fine( "J" );
			}
		catch ( Throwable gex )
			{
			logException( out, "Facility", "sendemail", 
			    "A technical problem occured.",
			    gex );
			}
		Logger.getLogger("org.bodington").fine( "K" );
		}
// javamail
*/

	}


