package com.evermind.ejb;

import java.util.*;
import java.rmi.RemoteException;
import javax.ejb.*;
import javax.naming.*;

public class NewsSessionEJB implements SessionBean
{
	private NewsItemHome news;
	
	public void ejbCreate() throws CreateException
	{
		try
		{
			news = (NewsItemHome)new InitialContext().lookup("java:comp/env/ejb/NewsItem");
		}
		catch(NamingException e)
		{
			throw new CreateException("NamingException: " + e.getMessage());
		}
	}

	public void ejbActivate()
	{
	}

	public void ejbPassivate()
	{
	}
	
	public void ejbRemove()
	{
	}
	
	public void setSessionContext(SessionContext context)
	{
	}
	
	public Collection getChildren(int parentID) throws RemoteException, FinderException
	{
		NewsItem parent = parentID == 0l ? null : news.findByPrimaryKey(parentID);
		
		Collection children = news.findByParent(parent);
		
		List childrenViews = new ArrayList();
		Iterator iterator = children.iterator();
		
		while(iterator.hasNext())
		{
			childrenViews.add(((NewsItem)javax.rmi.PortableRemoteObject.narrow(iterator.next(), NewsItem.class)).getView());
		}

		return childrenViews;
	}

	public NewsView getNews(int id) throws RemoteException, FinderException
	{
		return news.findByPrimaryKey(id).getView();
	}

	public NewsView addNews(int parentID, Date date, String subject, String content) throws CreateException, FinderException, RemoteException
	{
		return news.create(parentID != 0 ? news.findByPrimaryKey(parentID) : null, date, subject, content).getView();
	}
}
