/* ======================================================================
   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.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 org.bodington.util.IntStringEnum;

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
     */
    public static class UserFileEventType extends IntStringEnum
    {
        protected UserFileEventType(String name)
        {
            super(name, UserFileEventType.class);
        }
        
        public static UserFileEventType getMapping(int index)
        {
            return (UserFileEventType)getConst(index,UserFileEventType.class);
        }
        
        public static UserFileEventType getMapping(String name)
        {
            return (UserFileEventType)getConst(name, UserFileEventType.class);
        }
        
    }

	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.getMapping(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.getMapping(event_code).getName()),
            params));

		}

	}
	
