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

import java.util.Enumeration;
import java.util.Vector;

import org.bodington.database.PrimaryKey;
import org.bodington.server.BuildingServerException;
import org.bodington.server.BuildingSessionManagerImpl;
import org.bodington.server.Quota;
import org.bodington.server.QuotaExceededException;
import org.bodington.server.QuotaFactory;
import org.bodington.server.QuotaMetadatum;
import org.bodington.server.UploadedFileSession;
import org.bodington.server.realm.Permission;

/**
 * Decorator that adds quotas to ResourceTree
 * @author buckett
 */
public class ResourceTreeQuota implements ResourceTree
{
    private ResourceTree resourceTree;
    
    public ResourceTreeQuota(ResourceTree resourceTree)
    {
        this.resourceTree = resourceTree;
    }
    

    public synchronized void addResource(Resource parent, Resource newresource)
        throws BuildingServerException
    {
        if ( parent != null )
        {
            QuotaMetadatum quota = QuotaFactory.getQuota(parent, QuotaFactory.RESOURCES);
            checkQuota(parent, quota, 1);
            resourceTree.addResource(parent, newresource);
            quota.adjustUsage(1);
        }
        else
        {
            resourceTree.addResource(parent, newresource);
        }

    }

    public int countDescendents(PrimaryKey resource_id)
        throws BuildingServerException
    {
        return resourceTree.countDescendents(resource_id);
    }

    public Resource findResource(String delimited_name)
        throws BuildingServerException
    {
        return resourceTree.findResource(delimited_name);
    }

    public Resource findResource(String[] names) throws BuildingServerException
    {
        return resourceTree.findResource(names);
    }

    public Resource findRootResource() throws BuildingServerException
    {
        return resourceTree.findRootResource();
    }

    public boolean isInside(Resource a, Resource b)
        throws BuildingServerException
    {
        return resourceTree.isInside(a, b);
    }

    public void loadResources() throws BuildingServerException
    {
        resourceTree.loadResources();
    }

    public synchronized void moveResource(Resource newparent, Resource resource)
        throws BuildingServerException
    {
        QuotaMetadatum sourceResQuota = QuotaFactory.getQuota(resource, QuotaFactory.RESOURCES);
        QuotaMetadatum destResQuota = QuotaFactory.getQuota(newparent, QuotaFactory.RESOURCES);
        QuotaMetadatum sourceFileQuota = QuotaFactory.getQuota(resource, QuotaFactory.FILES);
        QuotaMetadatum destFileQuota = QuotaFactory.getQuota(newparent, QuotaFactory.FILES);
        
        boolean ignoreResources = sourceResQuota.getResource().equals(destResQuota.getResource());
        boolean ignoreFiles = sourceFileQuota.getResource().equals(destFileQuota.getResource());
        
        if (destResQuota.hasQuota())
            if (!sourceResQuota.hasQuota())
                throw new BuildingServerException("You cannot move resources from an area without a resource quota to an area with one.");
        
        int extraResources = sumResourceQuota(resource);
        if (!ignoreResources)
            checkQuota(newparent, destResQuota, extraResources);

        synchronized (sourceFileQuota.getLock())
        {
            int extraFiles = sumFileQuota(resource);
            synchronized (destFileQuota.getLock())
            {
                
                if (!ignoreFiles)
                    checkQuota(newparent, destFileQuota, extraFiles);
                resourceTree.moveResource(newparent, resource);
                if (!ignoreResources)
                {
                    destResQuota.adjustUsage(extraResources);
                    sourceResQuota.adjustUsage(-extraResources);
                }
                if (!ignoreFiles)
                {
                    destFileQuota.adjustUsage(extraFiles);
                    sourceFileQuota.adjustUsage(-extraFiles);
                }
            }
            
        }
        
    }

    public void removeResource(Resource r) throws BuildingServerException
    {
        resourceTree.removeResource(r);
    }

    public void sortResources(Resource parent, Vector siblings)
        throws BuildingServerException
    {
        resourceTree.sortResources(parent, siblings);
    }

    public boolean isDeleted(Resource resource) throws BuildingServerException
    {
        return resourceTree.isDeleted(resource);
    }

    private void checkQuota(Resource parent, QuotaMetadatum quota, int increase) throws QuotaExceededException
    {
        if (!parent.checkPermission(Permission.SYSADMIN) && quota.hasQuota() && !(quota.getUsage() + increase <= quota.getQuota()))
            throw new QuotaExceededException(quota, increase);
    }
    
    /*
     * Walk down the tree looking at the resource included in this quota
     */
    private int sumResourceQuota(Resource resource) throws BuildingServerException
    {
        Quota quota = QuotaFactory.getQuota(resource, QuotaFactory.RESOURCES);
        if (resource.equals(quota.getResource())) return 0;
        int sum = 1;
        Enumeration children = resource.findChildren();
        while (children.hasMoreElements())
        {
            sum += sumResourceQuota((Resource)children.nextElement());
        }
        return sum;
    }
        
    private int sumFileQuota(Resource resource) throws BuildingServerException
    {
        Quota quota = QuotaFactory.getQuota(resource, QuotaFactory.FILES);
        if (resource.equals(quota.getResource())) return 0;
        UploadedFileSession session = BuildingSessionManagerImpl.getSession(
            resource).getUploadedFileSession();
        UploadedFileSummary[] summaries = session
            .getFileAndDescendentSummaries((String) null, true);
        int sum = 0;
        for (int i = 0; i < summaries.length; i++)
        {
            sum += summaries[i].getSize();
        }
        Enumeration children = resource.findChildren();
        while (children.hasMoreElements())
        {
            sum += sumFileQuota((Resource)children.nextElement());
        }
        return sum;
        
    }
  
}
