/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

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

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.*;

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>" );
	            	out.print( DateFormatter.formatDate( event.getEventTime(), DateFormatter.MEDIUM ) );
	            	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 occurred in any locations on your notification list since "  );
			out.print( DateFormatter.formatDate( ues.getCutoffTime(), DateFormatter.DEFAULT ) );
			}

		}

	
	
	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>" );
	        out.print( DateFormatter.formatDate( job_result.getExecutionTime(), DateFormatter.MEDIUM ) );
		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;
		}

	    }

    public boolean isSysadmin()
    {
        return true;
    }
	}


