/* ======================================================================
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.server.resources;

import java.security.Principal;

import org.apache.log4j.Logger;
import org.bodington.server.BuildingContext;
import org.bodington.server.BuildingServerException;
import org.bodington.server.realm.Acl;
import org.bodington.server.realm.AclEntry;
import org.bodington.server.realm.Permission;
import org.bodington.servlet.FacilityList;
import org.bodington.servlet.Request;
import org.bodington.servlet.facilities.Facility;

/**
 * Helper functions that don't need to be in resource because they clutter the API
 * or make resource depend on packages it shouldn't.
 * @author buckett
 */
public class ResourceUtils
{
	private static Logger log = Logger.getLogger(ResourceUtils.class);
	 
    /**
     * Attempt to work out the URL for uploaded files.
     * Looks at the property <code>webpublish.webaddress</code>.
     * If it starts with a "/" then use it, otherwise prefix it with the context.
     * It doesn't at the moment support using a completly different URL.
     * @param resource The resource to get the path for.
     * @param request The request through which the call is being made.
     * @return A the path.
     * @throws BuildingServerException
     */
    public static String getWebPublishAddress(Resource resource, Request request)
    {
        String path = BuildingContext.getProperty( "webpublish.webaddress", "files/");
        if (!path.startsWith("/"))
        {
            path = request.getContextPath()+ "/" + path;
        }
        
        return path + resource.getResourceId().toString() + "/";
    }
    /**
     * Attempt to work out the URL for generated files.
     * Looks at the property <code>filegeneration.webaddress</code>.
     * If it starts with a "/" then use it, otherwise prefix it with the context.
     * It doesn't at the moment support using a completly different URL.
     * @param resource The resource to get the path for.
     * @param request The request through which the call is being made.
     * @return A the path.
     * @throws BuildingServerException
     */
    public static String getGeneratedFileAddress(Resource resource, Request request)
    {
        String path = BuildingContext.getProperty( "filegeneration.webaddress", "generated/");
        if (!path.startsWith("/"))
        {
            path = request.getContextPath()+ "/" + path;
        }
        return path + resource.getResourceId().toString() + "/";
    }
    
    /**
     * Attempt to grant some permissions to a Resource. This is often 
     * used by facilities to grant additional permissions on a resource straight after
     * it has been created. This method doesn't save the ACL after is has been
     * updated and it is up to the calling code.
     * @param resource The resource to add the permissions to.
     * @param grant An array of permissions to be added
     * @return True if the permissions were sucessfully added.
     */
    public static boolean grantPermissions(Resource resource, Permission[] grant)
    {
        try
        {
            Acl acl = resource.getAcl();
            if (acl != null)
            {
                AclEntry aclEntry = acl.getOwnerGroupAclEntry();
                if (aclEntry != null)
                {
                    for(int count = 0; count < grant.length; count++)
                    {
                        aclEntry.addPermission(grant[count]);
                    }
                    return true;
                }
            }
            log.warn("Resource doesn't have default ACLs: "+ resource);
        }
        catch (BuildingServerException bse)
        {
            log.warn("Could not get ACL details for: " + resource);
        }
        return false;
    }
    
    /**
     * Check to see if the current user has <em>any</em> of the supplied
     * permissions on supplied resource.
     * @param resource The Resource to perform the permission checks against.
     * @param check An array of permissions to check. If the array is empty 
     * false will be returned.
     * @return <code>true</code> if the current user has any of the permissions
     * on the supplied resource.
     */
    public static boolean anyPermission(Resource resource, Permission[] check)
    {
        for (int i = 0; i < check.length; i++)
            if (resource.checkPermission(check[i]))
                return true;
        return false;
    }
    
    /**
     * Check to see if any of the principals have the requested permission on the
     * supplied resource.
     * @param resource The resource to perform the check against.
     * @param principal An array of principals to check. Typically this will be groups.
     * @param permission The permission to test for.
     * @return <code>true</code> if the permission is had by any of the principals
     * on the resource, otherwise <code>false</code>.
     */
    public static boolean anyPrincipal(Resource resource, Principal principal[], Permission permission)
    {
        for (int i = 0; i < principal.length; i++)
            if (resource.checkPermission( principal[i], permission ))
                return true;
        return false;
    }
    
    public static Facility getFacility(Resource resource)
    {
        return FacilityList.getFacilities().get(new Integer(resource.getHttpFacilityNo()));
    }
    
    /**
     * Get a unique child name for the specified resource. This method will
     * examine the names of existing children of the <code>parent</code>
     * parameter. If no child has a name equal to the <code>childName</code>
     * parameter, then this is the value returned. Otherwise, the value returned
     * is the <code>childName</code> modified in order that it is unique
     * amongst it's siblings.
     * @param parent the parent of the child you wish to create.
     * @param childName the name to check for uniqueness.
     * @return a name which is unique amongst the existing children of the
     *         specified resource.
     */
    public static String getUniqueChildName( Resource parent, String childName )
        throws BuildingServerException
    {
        String prefix = childName, increment = "";
        // TODO: limit max number for 'start'?
        for ( int start = 2; parent.findChild( prefix + increment ) != null; start++ )
        {
            increment = Integer.toString( start );
            if ( (prefix + increment).length() > 12 )
                prefix = prefix.substring( 0, 12 - increment.length() );
        }

        return prefix + increment;
    }
}