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

	}
	
