/* ======================================================================
   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.bodington.servlet.*;

import org.apache.log4j.Logger;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

import org.bodington.server.*;
import org.bodington.server.realm.*;
import org.bodington.server.resources.*;

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

	public Resource newResource()
		{
		return new AliasEditor();
		}
	
	public boolean canCopy( Resource resource )
    {
        return false;
    }
	
/*
	public boolean create( Request breq, Connection con, Location newloc )
		throws Exception
		{
		BRealm realm=getRealm();

		// load the localgroup created by the Facility creation routine,
		// edit it and save to the database
		//Group group=new Group();
		//group.name=newloc.url;
		//group.location=newloc.id;
		//group.description=newloc.description;
		//group.type=null;
		//group.insert( con );
		// (the insert method fetches the new id)
		
		//realm.addGroup( group );
		
		return true;  
		}
*/

	public boolean clearCacheEntry( Object d, boolean force )
		{
		//no special clean up needed
		return true;
		}

	public void insert( Request req, PrintWriter out, String command, String insertname )
		throws ServletException, IOException
		{
		log.debug( " PermissionFacility insert()" );
			
		try
			{
			if ( command.equals( "groupprefix" ) )
				{
				String prefix = getPrefix();
				out.print( prefix );
				return;
				}

			if ( command.equals( "groupmemberimport" ) )
				{
				groupMemberImport( req, out );
				return;
				}
			}
		catch ( BuildingServerException bsex )
			{
			out.println( "Technical problem creating page.<HR>" );
			out.println( bsex.toString() );
			}
		
		super.insert( req, out, command, insertname );
		}
		

	public void groupMemberImport( Request req, PrintWriter out )
		throws IOException, BuildingServerException
		{
		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;

		String name, entries;
		
		try 
		    {
	        name = req.getParameter( "alias_name" );
	        um_session.setAliasName( name );
	        
	        entries = req.getParameter( "users" );
	        }
		catch ( BuildingServerException bsex )
		    {
		    logException( out, "GroupContainerFacility", "groupMemberImport", 
			"A technical problem occurred trying to process input." + bsex.friendlyMessage(),
			bsex );
		    return;
		    }

		try 
		    {
		    out.println( "<PRE>" );
		    um_session.addUsersToGroups( new BufferedReader( new StringReader( entries ) ), new PrintWriter( out ) );
		    out.println( "</PRE>" );
		    }
		catch ( BuildingServerException bsex )
		    {
		    out.println( "</PRE>" );
		    logException( out, "GroupContainerFacility", "groupMemberImport", 
			"A technical problem occurred trying to process input." + bsex.friendlyMessage(),
			bsex );
		    return;
		    }
		catch ( Exception ex )
		    {
		    out.println( "</PRE>" );
		    logException( out, "GroupContainerFacility", "groupMemberImport", 
			"A technical problem occurred trying to process input.",
			ex );
		    return;
		    }
		}


	
	public String getPrefix()
		throws BuildingServerException
		{
		StringBuffer name = new StringBuffer();
		boolean in_groups;
		BuildingContext context=BuildingContext.getContext();
		Resource resource = context.getResource();
		Resource current;
		Enumeration ancestors = resource.findAncestors();
		
		in_groups=false;
		while ( ancestors.hasMoreElements() )
			{
			current = (Resource)ancestors.nextElement();
			if ( in_groups )
				{
				if ( id.intValue() != current.getHttpFacilityNo() )
					{
					in_groups=false;
					name.setLength( 0 );
					continue;
					}
				name.append( current.getName() );
				name.append( "." );
				}
			else
				{
				if ( id.intValue() == current.getHttpFacilityNo() )
					{
					in_groups=true;
					name.setLength( 0 );
					name.append( current.getName() );
					name.append( "." );
					}
				}
			}
		return name.toString();
		}
		
    public boolean isSysadmin()
    {
        return true;
    }
    
	}


