/*
 * ====================================================================== 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.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.bodington.server.BuildingContext;
import org.bodington.server.BuildingServerException;
import org.bodington.server.BuildingSession;
import org.bodington.server.BuildingSessionManagerImpl;
import org.bodington.server.PermissionDeniedException;
import org.bodington.server.QuotaExceededException;
import org.bodington.server.events.ResourceEvent;
import org.bodington.server.realm.Permission;
import org.bodington.server.realm.User;

public class ResourceHierarchyImpl implements ResourceHierarchy
{
    
    private static Logger log = Logger.getLogger(ResourceHierarchyImpl.class);

    public boolean addResource(Resource parent, Resource child) throws BuildingServerException
    {
        ResourceTree tree = null;
        Connection con = null;
        
        // Check permission
        if (!parent.checkPermission(Permission.CREATE))
        {
            throw new PermissionDeniedException(Permission.CREATE);
        }
        
        try 
        {
            tree = ResourceTreeManager.getInstance();
        }
        catch (BuildingServerException bse)
        {
            log.warn("Failed to the get ResourceTree.", bse);
            return false;
        }
        
        try
        {
            BuildingContext context = BuildingContext.getContext();
            con = context.getConnection();

            con.setAutoCommit(false);
            tree.addResource(parent, child);

            ResourceEvent event = new ResourceEvent(ResourceEvent.EVENT_CREATE,
                child);
            event.setActiveUser((User) context.getUser());
            event.save();

            con.commit();

            BuildingSession session = BuildingSessionManagerImpl
                .getSession(child);
            session.updateBasicMetadata();
            
            return true;
        }
        catch (QuotaExceededException qee)
        {
            cleanup(child, tree, con, qee);
            throw qee;
        }
        catch (Exception e)
        {
            cleanup(child, tree, con, e);
            return false;
        }
        finally 
        {
            if (con != null)
            {
                try 
                {
                    con.setAutoCommit(true);
                }
                catch (SQLException sqle)
                {
                    log.warn("Failed to turn autocommit on.", sqle);
                }
            }
        }

    }

    private void cleanup(Resource child, ResourceTree tree, Connection con,
        Exception e)
    {
        log.error("Problem adding new resource: "+ e);
        try
        {
            tree.removeResource( child );
            if (con != null)
            {
                con.rollback();
            }
        }
        catch (Exception bse)
        {
            log.error("Failed to rollback changes: ", bse);
        }
    }

    public void copyResource(Resource source, Resource destination,
        boolean recursive)
    {
        // TODO Auto-generated method stub

    }

    public void moveResource(Resource resource, Resource newParent)
    {
        // TODO Auto-generated method stub

    }

}
