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

import org.bodington.database.*;
import org.bodington.sqldatabase.*;
import org.bodington.server.events.*;
import org.bodington.server.resources.*;
import org.bodington.server.realm.*;
import org.bodington.server.*;

import org.bodington.server.realm.User;

import java.util.Enumeration;
import java.io.PrintWriter;


public class LogBookEvent extends org.bodington.server.events.Event
	{
	PrimaryKey log_book_event_id;
	PrimaryKey log_book_entry_id;
	
	public static final int EVENT_MIN					     =1;
	
	public static final int EVENT_READ  					 =1;
	public static final int EVENT_POST  					 =2;
	public static final int EVENT_EDIT  					 =3;
	public static final int EVENT_POST_DRAFT  				 =4;
	public static final int EVENT_EDIT_DRAFT				 =5;
	public static final int EVENT_SELECT        			 =6;
	public static final int EVENT_CLOSE		       			 =7;
	public static final int EVENT_OPEN		       			 =8;
	public static final int EVENT_ADD_ITEM      			 =9;
	public static final int EVENT_EDIT_ITEM     			 =10;
	public static final int EVENT_DELETE_ITEM       		 =11;
	
	public static final int EVENT_MAX					     =11;
	
	
	static final String[] event_message_a = 
		{
		"",
		" read logbook entries",
		" posted a logbook entry",
		" edited a logbook entry",
		" posted a draft logbook entry",
		" edited a draft logbook entry",
		" selected for collation a logbook entry",
		" closed the log",
		" opened the log",
		" added a section or question to the logbook",
		" edited a section or question in the logbook",
		" deleted a section or question from the logbook"
		};
	
	static final String[] event_message_b = 
		{
		"",
		" in the log belonging to ",
		" in the log belonging to ",
		" in the log belonging to ",
		" in the log belonging to ",
		" in the log belonging to ",
		" in the log belonging to ",
		" belonging to ",
		" belonging to ",
		"",
		"",
		""
		};

	public static LogBookEvent findLogBookEvent( PrimaryKey key )
	    throws BuildingServerException
	    {
	    return (LogBookEvent)findPersistentObject( key, "org.bodington.logbook.server.LogBookEvent" );
	    }
	
	public static LogBookEvent findLogBookEvent( String where )
	    throws BuildingServerException
	    {
	    return (LogBookEvent)findPersistentObject( where, "org.bodington.logbook.server.LogBookEvent" );
	    }
	
	public static Enumeration findLogBookEvents( String where )
	    throws BuildingServerException
	    {
	    return findPersistentObjects( where, "org.bodington.logbook.server.LogBookEvent" );
	    }
	
	public static Enumeration findLogBookEvents( String where, String order )
	    throws BuildingServerException
	    {
	    return findPersistentObjects( where, order, "org.bodington.logbook.server.LogBookEvent" );
	    }




	
	public LogBookEvent()
		{
		super();
		log_book_entry_id=null;
		}
	
	public LogBookEvent(	int event_code, 
							PrimaryKey resource_id, 
							PrimaryKey active_user_id, 
							PrimaryKey passive_user_id, 
							PrimaryKey log_book_entry_id )
		{
		super();
		
		setEventCode( event_code );
		if ( event_code >= EVENT_MIN || event_code <= EVENT_MAX ) 
			setImportance( Event.IMPORTANCE_MANAGEMENT_MIN );
		if ( event_code == EVENT_POST || event_code == EVENT_CLOSE  || event_code == EVENT_OPEN )
			setImportance( Event.IMPORTANCE_USER_MIN );
			
		setResourceId( resource_id );
		setActiveUserId( active_user_id );
		setPassiveUserId( passive_user_id );
		this.log_book_entry_id  = log_book_entry_id;
		}
	
	
	
	
    public PrimaryKey getPrimaryKey()
	    {
        return getLogBookEventId();
    	}

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

	public PrimaryKey getLogBookEventId()
		{
		return log_book_event_id;
		}
		
    public void setLogBookEventId(PrimaryKey key)
    	{
    	log_book_event_id = key;
    	setEventId( key );
    	setUnsaved();
    	}



		
	public PrimaryKey getLogBookEntryId()
		{
		return log_book_entry_id;
		}
		
    public void setLogBookEntryId( PrimaryKey id )
    	{
    	log_book_entry_id = id;
    	setUnsaved();
    	}

		

	public String messageTitle()
		{
		int ecode = getEventCode();
		if ( ecode>=EVENT_MIN && ecode<=EVENT_MAX )
			return "Someone" + event_message_a[ecode] + ".";
		return "User accessed bodington system via a web page.";
		}

	public void printProperties( PrintWriter writer, boolean html )
		{
		super.printProperties( writer, html );
		
		if ( html )
			writer.println( "<PRE>" );
		writer.print( "Logbook Entry ID   : " );   writer.println( log_book_entry_id==null?"none":log_book_entry_id.toString() );
		if ( html )
			writer.println( "</PRE>" );
		}


	public void printMessage( PrintWriter writer, boolean html )
		{
		int ecode = getEventCode();

		User active = null;
		User passive = null;
		try
			{
			active = getActiveUser();
			passive = getPassiveUser();
			}
		catch ( BuildingServerException bsex )
			{
			// do nothing
			}

		if ( active==null )
			writer.print( "Someone" );
		else
			writer.print( active.getName() );
			
		if ( ecode>=EVENT_MIN && ecode<=EVENT_MAX )
			writer.print( event_message_a[ecode] );
		else
			{
			writer.print( " generated a logbook event." );
			return;
			}
		 
		if ( passive!=null )
			{
			writer.print( event_message_b[ecode] );
			writer.print( passive.getName() );
			}
			
		writer.print( "." );
		}
	

	public boolean checkPermission()
		{
		//default is to let importance level govern
		//who can see the event but if there is a more
		//complex algorithm subclass can overide this.
		//E.g. to allow a non-manager user to only see 
		//events relating to themselves.
		try
			{
			Resource resource = getResource();
			if ( resource.checkPermission( Permission.MANAGE ) ||
					resource.checkPermission( Permission.MARK )   )
				return true;
				
			User loguser = getPassiveUser();
			if ( loguser == null )
				return true;
				
			User user = (User)BuildingContext.getContext().getUser();
			return loguser.equals( user );
			}
		catch ( Exception ex )
			{
			return false;
			}
		}

	}
	
