/* ======================================================================
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.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

import org.bodington.database.*;
import org.bodington.server.*;
import org.bodington.server.realm.*;
import org.bodington.server.resources.Resource;
import org.bodington.server.userimport.AlreadyRunningException;
import org.bodington.server.userimport.ConfigurationException;
import org.bodington.server.userimport.ImportManager;
import org.bodington.server.userimport.NotInitialisedException;
import org.bodington.server.userimport.ScheduledImport;
import org.bodington.server.userimport.ldapir.LDAPInformationResource;
import org.bodington.server.userimport.xmlir.XMLInformationResource;



public class UserCreationFacility extends org.bodington.servlet.facilities.AliasFacility
	{
    
	private static Logger log = Logger.getLogger(UserCreationFacility.class);
	


	public Resource newResource()
		{
		return new AliasEditor();
		}
	


	public void insert( Request req, PrintWriter out, String command, String insertname )
		throws ServletException, IOException
		{
		
		log.debug( " AliasFacility insert()" );


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

		try
			{
			BuildingSession session;
			UserManagementSession um_session;

		    session = BuildingSessionManagerImpl.getSession( req.getResource() );
		    if ( !(session instanceof UserManagementSession) )
		    	{
		    	out.println( "<HR>Technical problem: unable to access appropriate tool session.<HR>" );
		    	return;
		    	}
		    um_session = (UserManagementSession)session;

			if ( command.equalsIgnoreCase( "createusers" ) )
		    	{
				createUsers( um_session, req, out );
		    	return;
		    	}
		    }
		catch ( BuildingServerException bsex )
			{
			out.println( bsex.toString() );
			return;
			}
		}
	
	
	public void createUsers( UserManagementSession um_session, Request req, PrintWriter out )
		throws ServletException, IOException
		{
		String name, type, entries, groups;
		
		try 
		    {
	        name = req.getParameter( "alias_name" );
	        um_session.setAliasName( name );
	        
	        type = req.getParameter( "type" );
	        um_session.setTypeName( type );
	        
	        entries = req.getParameter( "users" );
	        }
		catch ( BuildingServerException bsex )
		    {
		    out.println( bsex.friendlyMessage() );
		    log.error( bsex.toString() );
		    return;
		    }

		try 
		    {
	        out.println( "<FORM><SPAN CLASS=bs-textarea><TEXTAREA COLS=50 ROWS=10>" );
	        groups = um_session.createUsers( new BufferedReader( new StringReader( entries ) ),
	        					new PrintWriter( out ) );
		    out.println( "</TEXTAREA></SPAN></FORM>" );
		    out.println( "<P>The users have been added to the membership of these groups;</P>" );
		    out.println( "<P><B>" );
		    out.println( groups );
		    out.println( "</B><P>" );
		    }
		catch ( BuildingServerException bsex )
		    {
		    out.println( "</TEXTAREA></SPAN></FORM>" );
		    out.println( bsex.friendlyMessage() );
		    log.debug( bsex.toString() );
		    return;
		    }
		catch ( Exception ex )
		    {
		    out.println( "</TEXTAREA></SPAN></FORM><HR>Technical problem: " );
		    out.println( ex.toString() );
		    log.warn( ex.toString() );
		    return;
		    }
		}
	
	/**
	 * Check to see if the import is currently running.
	 * @return True if an import is currently running.
	 */
	public boolean isImporting() {
		return ImportManager.isRunning();
	}
	
	/**
	 * Check to see if the import is currently shutting down.
	 * @return True if an import is currently in shutdown.
	 */
	public static boolean isInShutdown() {
		return ImportManager.isInShutdown();
	}
	
	/**
	 * Get an import to be run at a later time.
	 * @return True if the import job was sucessfully setup.
	 */
	public static boolean scheduleImport(Request request, String prefix) {
		Calendar calendar = Utils.parseCalendarChooser(request, prefix);
		int repeat = Integer.parseInt(request.getParameter("repeat"));
        String impl = parseType(request);
		if (calendar != null) {
			try {
				ImportManager.init(BuildingServer.getInstance().getProperties());
			} catch (AlreadyRunningException e) {
				log.info("Didn't initialise import manager as it's already running");
			} catch (ConfigurationException e) {
				log.info("Error in configuration. Job might run?");
			}
			try
			{
			JobScheduler jobScheduler = JobScheduler.getJobScheduler(false);
			jobScheduler.addJob(
					ScheduledImport.class.getName(),
					"run",
					impl,
					repeat,
					calendar
					);
			}
			catch (BuildingServerException bse)
			{
			    log.error("Failed to schedule job.", bse);
            }
		}
		return true;
	}



    /**
     * Attempts to parse the type parameter. This should give the class
     * that should be used.
     * @param request The request that might contain the type.
     * @return A String of the type of import to run, null if we couldn't find
     * anything or it didn't match a known type..
     */
    private static String parseType(Request request)
    {
        String impl = null;
        try
        {
            int type = Integer.parseInt(request.getParameter("type"));
            switch (type)
            {
                case 0:
                    impl = LDAPInformationResource.class.getName();
                    break;
                case 1:
                    impl = XMLInformationResource.class.getName();
                    break;
            }
        }
        catch (NumberFormatException nfe){}
        
        return impl;
    }
	
	/**
	 * Attempt to remove an import from the Job queue.
	 * @return True if the jobs was sucessfully removed.
	 */
	public static boolean removeImport(Request request) {
		int id = Integer.parseInt(request.getParameter("jobId"));
		try {
			Job job = Job.findJob(new PrimaryKey(id));
			job.setState(Job.STATE_CANCELLED);
			job.save();
			return true;
		} catch (BuildingServerException e) {
			log.warn("Failed to remove job: "+ id);
		}
		return false;
	}
	
	/**
	 * Attempts to display all the import jobs that are going to happen in the future.
	 * Really this should all be in the templates but it seems they don't have the 
	 * ability todo proper looping.
	 * @param out Where all the HTML is written.
	 */
	public static void showFutureImports(PrintWriter out) 
	{
		try {
		    if (JobScheduler.getJobScheduler(false) == null)
		    {
		        out.write("<strong>Job Scheduler is not running</strong>");
		        return;
		    }
			Enumeration jobs = Job.findJobs(ScheduledImport.class.getName(),"run",true);

			if (jobs == null){
				return;
			}
			out.write("<ul>\n");
			while(jobs.hasMoreElements()) {
				out.write("<li>");
				final Job job = (Job)jobs.nextElement();
                out.write(job.getParameter());
                out.write("<br>");
				out.write(job.getScheduleDescription());
				out.write("<br/><font size=\"-2\">");
				out.write("<a href=\"bs_template_remove_import.html?jobId=");
				out.write(job.getPrimaryKey().toString());
				out.write("\">Delete</a></font>");
				out.write("</li>\n");
			}
			out.write("</ul>\n");
		} catch (BuildingServerException e) {
		}
		
	}
	
	/**
	 * Returns the current status of the Import.
	 * @return A HTML string describing the current status of the import.
	 */
	public void getStatus(PrintWriter pw) {
		StringBuffer output = new StringBuffer();
		int[] progress = ImportManager.progress();
		output.append("<pre>");
		output.append("Users processed: ");
		output.append(progress[0]);
		output.append("\n");
		output.append("Groups created:");
		output.append(progress[1]);
		output.append("\n");
		output.append("Resources created:");
		output.append(progress[2]);
		output.append("</pre>");
		output.append("Running for: ");
		long duration = Calendar.getInstance().getTimeInMillis() - ImportManager.getStarted().getTimeInMillis();
		output.append(duration/60000);
		output.append(" minutes. <br/>");
		pw.print(output);

	}
		
	/**
	 * Starts an import of users.
	 * Sets up the Import Manager using the same properties as
	 * the BuildServer.
	 * @return True if the import started sucessfully.
	 */
	public boolean startImport(Request request) {
		log.info("Starting Import");
        String impl = parseType(request);
		try {
            Properties props = new Properties(BuildingServer.getInstance().getProperties());
            if (impl != null)
                props.setProperty("usrgrpgen.informationresource.impl", impl);
			ImportManager.init(props);
			ImportManager.start();
			return true;
		} catch (AlreadyRunningException e) {
			log.warn("Attempted to start an import when it is already running");
		} catch (ConfigurationException e) {
			log.warn("Invalid Import Configuration: "+e);
		} catch (NotInitialisedException e) {
			log.error("ImportManager is not setup. We should never get here.");
		}
		return false;
	}
	
	/**
	 * Attempts to halt the currently running import. This doesn't 
	 * stop the import straight away, just when the import loop gets
	 * around to trying another user.
	 * @return True if the import was sucessfully stopped.
	 */
	public void stopImport() {
		log.info("Stopping Import");
		ImportManager.dieDieDie();
	}


}


