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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.security.acl.NotOwnerException;

import org.apache.log4j.Logger;
import org.bodington.server.realm.AclEntry;
import org.bodington.server.realm.Group;
import org.bodington.server.realm.PassPhrase;
import org.bodington.server.realm.Permission;
import org.bodington.server.realm.User;
import org.bodington.server.realm.WebAuthUser;
import org.bodington.server.resources.HomeResource;
import org.bodington.server.resources.Resource;
import org.bodington.server.resources.ResourceTreeManager;
import org.bodington.server.resources.UploadedFileSummary;
import org.bodington.servlet.FacilityList;

public class HomeContainerSessionImpl extends BuildingSessionImpl implements HomeContainerSession
{

    private static Logger log = Logger.getLogger(HomeContainerSessionImpl.class);
    
    public static final String QUOTA_FILES = "homecontainer.quota.files";
    public static final String QUOTA_RESOURCES = "homecontainer.quota.resources";
    private final int files_quota;
    private final int resources_quota;
    
    public HomeContainerSessionImpl()
    {
        super();
        files_quota = BuildingContext.getProperty(QUOTA_FILES, 10000000, true);
        resources_quota = BuildingContext.getProperty(QUOTA_RESOURCES, 3000, true);
    }

    public boolean hasHome(User user) throws BuildingServerException
    {
        return findHome(user) != null;
    }

    /**
     * Creates a home container in this resource for a user. At the moment
     * the strings in the resource are hard coded.
     */
    public void createHome(User user) throws BuildingServerException
    {
        if (!getResource().checkPermission(Permission.CREATE))
            throw new PermissionDeniedException(Permission.CREATE);
        if (hasHome(user))
            throw new BuildingServerException("Resource already exists for: "+ user);
        
        String url = mapUserToURL(user);
        
        
        HomeResource resource = newResource();
        resource.setName(url);
        resource.setTitle("");
        resource.setDescription("Space for "+ user);
        resource.setIntroduction("This is your space");
        resource.setUserId(user.getUserId());

        ResourceTreeManager.getInstance().addResource(getResource(), resource);
        
        BuildingSession resourceSession = BuildingSessionManagerImpl.getSession(resource);
        resourceSession.getUploadedFileSession().setQuota(files_quota);
        resourceSession.setQuota(resources_quota);
        
        createDefaultResources(resource);
        
    }

    private void createDefaultResources(HomeResource resource) throws BuildingServerException
    {
        // Create some default resources.
        
        // The Public Resource
        Resource publicResource = new Resource();
        publicResource.setHttpFacilityNo(FacilityList.getFacilities().get("suite").id.intValue());
        publicResource.setName("public");
        publicResource.setTitle("Public Space");
        publicResource.setDescription("Space for content accessible by eveyone");
        publicResource.setIntroduction("Public Space");
        ResourceTreeManager.getInstance().addResource(resource, publicResource);
        
        Group group = Group.findGroupByName("public");
        AclEntry aclEntry=new AclEntry();
        aclEntry.setPrincipal( group );
        aclEntry.addPermission(Permission.SEE);
        aclEntry.addPermission(Permission.VIEW);
        try
        {
            publicResource.getAcl().addEntry( aclEntry );
        }
        catch (NotOwnerException e)
        {
            log.warn("Failed to add public acl", e);
        }
        publicResource.getAcl().save();
        
        Resource privateResource = new Resource();
        privateResource.setHttpFacilityNo(FacilityList.getFacilities().get("suite").id.intValue());
        privateResource.setName("private");
        privateResource.setTitle("Private Space");
        privateResource.setDescription("Space for content accessible by only you");
        privateResource.setIntroduction("Private Space");
        ResourceTreeManager.getInstance().addResource(resource, privateResource);
    }

    public Resource findHome(User user) throws BuildingServerException
    {
        Resource resource = HomeResource.findHomeResource(user, getResource());
        // TODO We should check if the resource is deleted.
        return resource;
    }
    
    private String mapUserToURL(User user)
    {
        String name = null;
        try
        {
            WebAuthUser waUser = WebAuthUser.findWebAuthUser( user );
            if (waUser != null)
                name = waUser.getUserName();
            else
            {
                PassPhrase passPhrase = PassPhrase.findPassPhrase(user);
                if (passPhrase != null)
                    name = passPhrase.getUserName();
            }
        }
        catch (BuildingServerException e)
        {
            log.error("Problem finding WebAuthUser for: "+ user, e);
        }
        return name;
    }
    
    public String getTerms(User user) throws BuildingServerException
    {
        UploadedFileSummary fileSummary = getUploadedFileSession().getFileSummary("/terms.html");
        if (fileSummary != null)
        {
            File file = getUploadedFileSession().getFile(fileSummary.getPrimaryKey());
            FileInputStream input = null;
            try
            {
                input = new FileInputStream(file);
                FileChannel channel = input.getChannel();
                MappedByteBuffer buffer = 
                    channel.map(MapMode.READ_ONLY, 0, (int)channel.size());
                CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
                return decoder.decode(buffer).toString();
            }
            catch (FileNotFoundException e)
            {
                log.error("Could not file uploaded file: "+ file);
            }
            catch (IOException e)
            {
                log.error("Failed to read file: "+ file, e);
            }
            finally
            {
                if (input != null)
                {
                    try
                    {
                        input.close();
                    }
                    catch (IOException ioe)
                    {
                        log.error("Problem closing stream on file: "+ file, ioe);
                    }
                }
            }
            throw new BuildingServerException("Failed to load terms.");
        }
        else
            log.info("Couldn't find terms and conditions file");
        return null;
    }
    
    public boolean canCreateHome(User user) throws BuildingServerException
    {
       return !hasHome(user) &&
           getResource().checkPermission(user, Permission.CREATE) &&
           mapUserToURL(user) != null;
    }
    
    private HomeResource newResource()
    {
        HomeResource resource = new HomeResource();
        resource.setHttpFacilityNo(FacilityList.getFacilities().get("home").id.intValue());
        return resource;
    }
    

}
