/* ======================================================================
   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.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.oucsir.OUCSInformationResource;



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(), ex );
		    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 2:
                    impl = OUCSInformationResource.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, 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();
	}
    
    public boolean isSysadmin()
    {
        return true;
    }

    public void outputGroupYear(PrintWriter out) {
        String incrementString = BuildingServer.getInstance().getProperty("usrgrpgen.grpmgr.increment.year");
        String year = "unknown";
        if (incrementString != null) {
            boolean increment = Boolean.valueOf(incrementString).booleanValue();
            year = Integer.toString(Calendar.getInstance().get(Calendar.YEAR) + ((increment)?0:-1));
        }
        out.print(year);
    }

}


