/* ======================================================================
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 org.apache.log4j.Logger;

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
	{
	
    private static Logger log = Logger.getLogger(NotificationFacility.class);

    public boolean canCopy( Resource resource )
    {
        return true;
    }
    
	public void insert( Request req, PrintWriter out, String command, String insertname )
		throws ServletException, IOException
		{
		log.debug( 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 enumeration = ues.findResources();
            Event event;
            PrintWriter writer = new PrintWriter( out );
            for ( location=0; enumeration!=null && enumeration.hasMoreElements(); location++ )
            	{
            	res = (Resource) enumeration.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;
		}

	    }

	}


