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

import org.bodington.server.BuildingContext;
import org.bodington.server.BuildingServerException;
import org.bodington.server.realm.Group;
import org.bodington.server.realm.Permission;
import org.bodington.server.resources.Resource;

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

	static final int LISTSTYLE_NORMAL=0;
	static final int LISTSTYLE_DELETE=1;
	static final int LISTSTYLE_SID=2;
	static final int LISTSTYLE_UID=3;
	static final int LISTSTYLE_SURNAME=4;
	static final int LISTSTYLE_MODULE=5;

	static private int container_facility_no=27;

	/**
     * Group editors and group containers will refuse to be initialised
     *
     * @param original The resource with properties to copy.
     * @param new_resource The resource to initialise.
     * @return True if initialisation was OK.
     * @exception BuildingServerException Thrown if there is any problem initialising the resource.
     *
     */
	public boolean initResource( Resource original, Resource new_resource)
		throws BuildingServerException
    {
        return false;
    }


	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 ( current.getHttpFacilityNo() != 27  )
					{
					in_groups=false;
					name.setLength( 0 );
					continue;
					}
				name.append( current.getName() );
				name.append( "." );
				}
			else
				{
				if ( current.getHttpFacilityNo()==27 )
					{
					in_groups=true;
					name.setLength( 0 );
					name.append( current.getName() );
					name.append( "." );
					}
				}
			}
		return name.toString();
		}


	public boolean createCheck( Request breq, PrintWriter out )
		{
		try
			{
			String name = breq.getParameter( "url" );
			String prefix = getPrefix();
			if ( prefix==null || prefix.length()<1 )
				{
				log.debug( "Prefix = [" + prefix + "]" );
				out.println( "Unexpected technical problem - unable to determine prefix for group name." );
				return false;
				}
			name = prefix + name;
			if ( name.length()>64 )
				{
				out.println( 
					"The full name of the group, <B>" + name + 
					"</B>is more than the allowed 64 characters in length." );
				return false;
				}
            
            String description = breq.getParameter( "description" );
            if (description == null || description.length()<1)
                {
                out.println("Description cannot be more that 128 characters, you currenlty have "+ description.length()+ " characters.");
                return false;
                }
			}
		catch ( Exception ex )
			{
			return false;
			}
		return true;
		}

	public boolean create( Request breq, Connection con, Resource new_resource )
		throws Exception
		{
		String prefix = getPrefix();
		if ( prefix==null || prefix.length()<1 )
			{
			log.debug( "Prefix = [" + prefix + "]" );
			return false;
			}
		String name = prefix + new_resource.getName();
			
		Group group=new Group();
		group.setResourceId( new_resource.getResourceId() );
		group.setName( name );
		group.setDescription( new_resource.getDescription() );
		new_resource.setTitle( group.getName() );
		new_resource.save();
		group.save();
		
		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( "grouptable" ) )
				{
				groupTable( req, out );
				}
			if ( command.equals( "confirmaddgroup" ) )
				{
				confirmAddGroup( req, out );
				}
			}
		catch ( BuildingServerException bsex )
			{
			out.println( "Technical problem creating page.<HR>" );
			out.println( bsex.toString() );
			}
		
		super.insert( req, out, command, insertname );
		}
		
	public void groupTable( Request req, PrintWriter out )
		throws ServletException, BuildingServerException, IOException
		{
		Enumeration enumeration = Group.findGroups( "resource_id = " + req.getResource().getResourceId() );
		Group group;

		Vector group_list = new Vector();
		while ( enumeration.hasMoreElements() )
			{
			group = (Group)enumeration.nextElement();
			if ( group.isLocalGroup() )
				continue;
			group_list.addElement( group );
			}
		
		
        //out.print( "<form method=post action=addgroup.html>" );
        //out.println( "<INPUT TYPE=SUBMIT VALUE=\"Add New Group\"></FORM>" );
		
		if ( group_list.size()==0 )
			{
			out.println( "<P>There are currently no groups here.</P>" );
			return;
			}

		enumeration = group_list.elements();
			
		out.println( "<TABLE CLASS=bs-table-opaque><TR>" );
		out.println( "<TD CLASS=bs-cell-special><strong>Name</strong></TD>" );
		out.println( "<TD CLASS=bs-cell-special><strong>Description</strong></TD>" );
		out.println( "<TD CLASS=bs-cell-special><strong>Membership</strong></TD></TR>" );
		
		while ( enumeration.hasMoreElements() )
			{
			group = (Group)enumeration.nextElement();
			out.print( "<TR><TD>" );
			out.print( group.getName() );
			out.print( "</TD><TD>" );
			out.print( group.getDescription() );
			out.print( "</TD>\n<TD>" );
            out.print( "<font size=2><form method=post ACTION=bs_template_accessgroup.html target=groupwindow>" );
            out.print( "<input type=hidden name=group_id value=" );
            out.print( group.getGroupId().toString() );
            out.print( "><INPUT TYPE=SUBMIT VALUE=\" Membership \" ONCLICK=\"grpwin()\"></FORM>" );
            out.println( "</font></td></TR>" );
			}

		out.println( "</TABLE>" );

		
		}
		
	public void confirmAddGroup( Request req, PrintWriter out )
		throws ServletException, BuildingServerException, IOException
		{
		if ( !req.getResource().checkPermission( Permission.EDIT ) )
			{
			out.println( "You don't have EDIT level permission here." );
			return;
			}
			
		String name, description;
		Group newgroup;
		
		
		name = req.getParameter( "name" );
		description = req.getParameter( "description" );
		
		newgroup = new Group();
		newgroup.setResourceId( req.getResource().getResourceId() );
		newgroup.setName( name );
		newgroup.setDescription( description );
		newgroup.setSpecialGroup( null );
		newgroup.save();
		
		out.println( "Confirmation: group created" );
		}
	}


