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

import org.bodington.database.PrimaryKey;
import org.bodington.server.BuildingServerException;
import org.bodington.util.*;

public class MessageTreeNode extends org.bodington.util.VisitationMutableTreeNode
	{
	
    public void setVisitationObject(VisitationObject v)
    	{
    	if ( !(v instanceof Message) )
    		throw new ClassCastException( "Can't store anything other than a Message in a MessageTreeNode" );
    	super.setVisitationObject( v );
    	}

	public void add( Message message )
		throws BuildingServerException
		{
		// make a new node for the message, add it
		// to the tree and update the date/time on
		// the path of messages to the root.
		MessageTreeNode node  = new MessageTreeNode();
		node.setVisitationObject( message );
		this.add( node );
		//should only be touching nodes whose indexes have
		//changed so don't need to mark as unsaved again.
		//touch is just to update the date.
		this.touch();
		}
		
	private void touch()
		throws BuildingServerException
		{
		Message message=null;
		PrimaryKey mid;
		
		mid = getPrimaryKey();
		if ( mid!=null )
			{
			message = Message.findMessage( mid );
			if ( message!=null )
				message.setUpdatedTime( new java.sql.Timestamp( System.currentTimeMillis() ) );
			}
		
		if ( !this.isRoot() )
			{
			MessageTreeNode node = (MessageTreeNode)this.getParent();
			if ( node!=null )
				node.touch();
			}
		}
	}
