/* ======================================================================
   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 java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.bodington.database.PrimaryKey;
import org.bodington.server.BuildingContext;
import org.bodington.server.BuildingServerException;
import org.bodington.server.realm.User;
import org.bodington.server.resources.Resource;
import org.bodington.util.IntStringEnum;


/**
 * Export Events are used to track events relating to users exporting content
 * @author Colin Tatham
 */
public class ExportEvent extends Event
{
	private static Logger log = Logger.getLogger(ExportEvent.class);
	private static ResourceBundle resourceBundle = ResourceBundle.getBundle(ExportEvent.class.getName());


	PrimaryKey export_event_id;
	String item_name;
    
	public static class ExportEventType extends IntStringEnum
	{
        protected ExportEventType(String name)
        {
            super(name, ExportEventType.class);
        }
        
        public static ExportEventType getMapping(int index)
        {
            return (ExportEventType)getConst(index,ExportEventType.class);
        }
        
        public static ExportEventType getMapping(String name)
        {
            return (ExportEventType)getConst(name, ExportEventType.class);
        }
        
    }

	public static final ExportEventType EVENT_ADD_RESOURCE_TO_ZIP = new ExportEventType("event.add.resource");
	public static final ExportEventType EVENT_ADD_FOLDER_TO_ZIP = new ExportEventType("event.add.folder");
    public static final ExportEventType EVENT_ADD_FILE_TO_ZIP = new ExportEventType("event.add.file");
	public static final ExportEventType EVENT_EXPORT_ASSESSMENT = new ExportEventType("event.export.assessment");
    
    public static Event findEvent( PrimaryKey key )
    throws BuildingServerException
    {
        return (Event)findPersistentObject( key, "org.bodington.server.events.ExportEvent" );
    }
    
    public static Event findEvent( String where )
    throws BuildingServerException
    {
        return (Event)findPersistentObject( where, "org.bodington.server.events.ExportEvent" );
    }
    
    public static Enumeration findEvents( String where )
    throws BuildingServerException
    {
        return findPersistentObjects( where, "org.bodington.server.events.ExportEvent" );
    }
    
    public static Enumeration findEvents( String where, String order )
    throws BuildingServerException
    {
        return findPersistentObjects( where, order, "org.bodington.server.events.ExportEvent" );
    }
    
    public static Enumeration findEventPrimaryKeys( String where, String order )
    throws BuildingServerException
    {
        return findPrimaryKeys( where, order, "org.bodington.server.events.ExportEvent" );
    }
    
    /**
     * Find events for a resource after a particular date. The results are sorted
     * by the time the event occurred.
     * @param resourceId The resource ID to find events for.
     * @param from The time to start looking from.
     * @return An Enumeration of Events.
     */
    public static Enumeration findEvents( PrimaryKey resourceId, long from )
    throws BuildingServerException
    {
    	return findEvents("resource_id = "+ resourceId+ " AND event_time > {ts '"+ new Timestamp(from)+ "'}", "event_time");
    }
    
    public ExportEvent()
    {
    	super();
    	item_name=null;
    }
	
	public ExportEvent( ExportEventType event_code, PrimaryKey resource_id, PrimaryKey user_id, String name )
	{
		super();

		this.event_code = event_code.getId(); 
		this.importance = Event.IMPORTANCE_MANAGEMENT_MIN;

		this.resource_id=resource_id;
		active_user_id=user_id;
		passive_user_id=null;

		this.item_name = name;
	}
	
	/**
	 * Basic constructor to create an export event in a particular resource.
	 * @param event_code
	 * @param resource
	 */
	public ExportEvent( ExportEventType event_code, Resource resource )
	{
		super();
		setEventCode(event_code.getId());
		setResource(resource);
		setImportance(Event.IMPORTANCE_MANAGEMENT_MIN);
		this.active_user_id = ((User)BuildingContext.getContext().getUser()).getPrimaryKey();
		setItemName( resource.getName() );
	}
	
	
    public PrimaryKey getPrimaryKey()
	    {
        return getExportEventId();
    	}

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

	public PrimaryKey getExportEventId()
		{
		return export_event_id;
		}
		
    public void setExportEventId(PrimaryKey key)
    	{
    	export_event_id = key;
    	setEventId( key );
    	setUnsaved();
    	}


	public void setItemName( String name )
		{
        if ( name == null )
            item_name = null;
        else
        {
            if ( name.length()<=128 )
                item_name = name;
            else
                item_name = name.substring( 128 );
        }
    	setUnsaved();
		}
		
	public String getItemName()
		{
		return item_name;
		}
	
		
	public void printProperties( PrintWriter writer, boolean html )
		{
		super.printProperties( writer, html );
		
		if ( html )
			writer.println( "<PRE>" );
		writer.print( "Name           : " );   writer.println( item_name==null?"no name":item_name );
		if ( html )
			writer.println( "</PRE>" );
		}

    public String messageTitle()
    {
        String params[] = {"Someone", "Some resource"};
        return MessageFormat.format(resourceBundle
            .getString(ExportEventType.getMapping(event_code).getName()),
            params);
    }
    
    public void printMessage(PrintWriter out, boolean html)
    {
    	Object params[] = new Object[2]; 
    	params[0] = "Someone";
    	params[1] = "Some resource";

    	try
    	{
    		params[0] = getActiveUser();
    		params[1] = getItemName();
    	}
    	catch ( BuildingServerException bsex )
    	{
    		// do nothing
    	}

    	out.write(MessageFormat.format(resourceBundle
    			.getString(ExportEventType.getMapping(event_code).getName()),
    			params));    	
    }
}