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

import org.bodington.database.*;
import org.bodington.sqldatabase.*;
import org.bodington.server.realm.User;
import org.bodington.server.resources.Resource;
import org.bodington.server.resources.UploadedFileSummary;
import org.bodington.server.BuildingContext;
import org.bodington.server.BuildingServerException;

import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import java.io.PrintWriter;

/**
 * Class to store events relating to uploaded file.
 * @author Jon Maber
 * @author buckett
 */
public class UserFileEvent extends Event
	{
	private PrimaryKey user_file_event_id;
	private Integer file_entry_id;
	private BigInteger file_size;
	private String file_name;
	
    private static ResourceBundle resourceBundle = ResourceBundle
        .getBundle(UserFileEvent.class.getName());
    
    public static final UserFileEventType EVENT_UPLOAD = new UserFileEventType(
        "event.upload");
    public static final UserFileEventType EVENT_DOWNLOAD = new UserFileEventType(
        "event.download");
    public static final UserFileEventType EVENT_DELETE = new UserFileEventType(
        "event.delete");
    public static final UserFileEventType EVENT_EDIT = new UserFileEventType(
        "event.edit");
    public static final UserFileEventType EVENT_UPLOAD_ZIP = new UserFileEventType(
        "event.upload.zip");
    public static final UserFileEventType EVENT_FOLDER_CREATED = new UserFileEventType(
        "event.folder.created");

    /**
     * Internal class used for the type constants.
     * @author buckett
     */
    private static class UserFileEventType
    {
        private static volatile int nextId = 0;
        private static List all = new ArrayList();
        private int id;
        private String name;
        
        /**
         * Standard constructor.
         * @param name The name to use in ResourceBundle lookups.
         */
        public UserFileEventType (String name)
        {  
            this.id = nextId++;
            this.name = name;
            all.add(id, this);
        }
        
        /**
         * Constructor for unknown type.
         * @param id The ID that doesn't match.
         */
        private UserFileEventType( int id )
        {
            this.id = id;
            this.name = "event.unknown";
        }
        
        public int getId()
        {
            return id;
        }
        
        public String getName()
        {
            return name;
        }
        
        public static UserFileEventType getConst(int id)
        {
            try
            {
                return (UserFileEventType)all.get(id);                
            }
            catch (IndexOutOfBoundsException iooe)
            {
                return new UserFileEventType(id);
            }
            
        }
    }

	public UserFileEvent()
		{
		super();
		}
	
	public UserFileEvent( UserFileEventType event_const, PrimaryKey resource_id, PrimaryKey active_user_id, 
							PrimaryKey passive_user_id, 
							Integer file_entry_id, BigInteger file_size, String file_name )
		{
		super();
		
		this.event_code = event_const.getId();
		this.importance = Event.IMPORTANCE_MANAGEMENT_MIN;
			
		this.resource_id=resource_id;
		this.active_user_id=active_user_id;
		this.passive_user_id=passive_user_id;
		
		this.file_entry_id = file_entry_id;
		this.file_size = file_size;
		setFileName( file_name );
		}
	
    /**
     * An easy way to create an event for a UploadedFile.
     * This constructor sets the active user from the BuildingContext.
     * Maybe this should be in a utility class to removed the dependancy
     * between UploadedFileSummary, BuildingContext and Events?
     * @param summary The uploaded file.
     */
    public UserFileEvent( UserFileEventType eventConst, Resource resource, UploadedFileSummary summary )
        {
        setEventCode(eventConst.getId());
        setResource(resource);
        setFileSummary(summary);
        setImportance(Event.IMPORTANCE_MANAGEMENT_MIN);
        this.active_user_id = ((User)BuildingContext.getContext().getUser()).getPrimaryKey();
        }
	
	
	
    public PrimaryKey getPrimaryKey()
	    {
        return getUserFileEventId();
    	}

    public void setPrimaryKey( PrimaryKey key )
    	{
    	setUserFileEventId( key );
    	}

	public PrimaryKey getUserFileEventId()
		{
		return user_file_event_id;
		}
		
    public void setUserFileEventId(PrimaryKey key)
    	{
    	user_file_event_id = key;
    	setEventId( key );
    	setUnsaved();
    	}


	public Integer getFileEntryId()
		{
		return file_entry_id;
		}
		
    public void setFileEntryId( Integer e )
    	{
    	file_entry_id = e;
    	setUnsaved();
    	}


	public BigInteger getFileSize()
		{
		return file_size;
		}
		
    public void setFileSize( BigInteger s )
    	{
    	file_size = s;
    	setUnsaved();
    	}


	public void setFileName( String u )
		{
		if ( u==null || u.length()<64 )
			file_name = u;
		else
			file_name = u.substring( 0, 60 ) + "...";
		setUnsaved();
		}
		
	public String getFileName()
		{
		return file_name;
		}
		
    /**
     * Sets the properties of this event from an already uploaded file.
     * @param summary The UploadedFileSummary that this event is for.
     */
	public void setFileSummary( UploadedFileSummary summary )
        {
        setFileEntryId(new Integer(summary.getUploadedFileId().intValue()));
        setFileName(summary.getName());
        setFileSize(BigInteger.valueOf(summary.getSize()));
        }

	public String messageTitle()
		{
            String params[] = {"Someone", getFileName(), "Someone" };
			return MessageFormat.format(resourceBundle
                .getString(UserFileEventType.getConst(event_code).getName()),
                params);
		}

	public void printProperties( PrintWriter writer, boolean html )
		{
		super.printProperties( writer, html );
		
		if ( html )
			writer.println( "<PRE>" );
		writer.print( "File entry id : " );   writer.println( file_entry_id==null?"no file entry of":file_entry_id.toString() );
		writer.print( "File size     : " );   writer.println( file_size==null    ?"no file size"    :file_size.toString()     );
		writer.print( "File name     : " );   writer.println( file_name==null    ?"no file name"    :file_name                );
		if ( html )
			writer.println( "</PRE>" );
		}
		
	public void printMessage( PrintWriter writer, boolean html )
		{
        Object params[] = new Object[3]; 
		params[0] = "Someone";
        params[1] = getFileName();
		params[2] = "Someone";
        

		try
			{
			params[0] = getActiveUser();
			params[2] = getPassiveUser();
			}
		catch ( BuildingServerException bsex )
			{
			// do nothing
			}
        
        writer.print(MessageFormat.format(resourceBundle
            .getString(UserFileEventType.getConst(event_code).getName()),
            params));

		}

	}
	
