/* file name  : chat/src/plugin/ChatPlugin.java
 * authors    : Kohji Tsujita
 * created    : 2009Ç¯09·î01Æü 16»þ11Ê¬24ÉÃ
 * copyright  : Kohji Tsujita
 *
 * modifications:
 *
 */
package chat.plugin;

import java.util.List;
import java.util.ArrayList;
import java.io.IOException;

import jp.maru.liquid.plugin.http.HttpRequest;
import jp.maru.liquid.plugin.http.HttpResponse;
import jp.maru.liquid.plugin.http.AsyncHttpEvent;
import jp.maru.liquid.plugin.http.AsyncTrigger;
import jp.maru.liquid.plugin.AsyncHttpServerPlugin;
import jp.maru.liquid.plugin.HttpBasicPlugin;

public class ChatPlugin implements AsyncHttpServerPlugin,HttpBasicPlugin
{
	private List<AsyncTrigger> _triggerList=new ArrayList<AsyncTrigger>();
	private String _lastMessage;
	private String _bindURI;

	@Override
	public void init()
	{
	}

	@Override
	public void execute(HttpRequest request,HttpResponse response)
	throws IOException
	{
		response.addHeader("Cache-Control","no-cache");
		response.addHeader("pragma","no-cache");
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().println(_lastMessage != null? _lastMessage: "");
	}

	@Override
	public void httpConnected(AsyncHttpEvent event,AsyncTrigger trigger)
	{

		_triggerList.add(trigger);
	}

	@Override
	public void httpDisconnected(AsyncHttpEvent event)
	{
	}

	public synchronized void message(String handle,String message)
	{
		try
		{
			_lastMessage=handle+": "+message;

			for(AsyncTrigger trigger : _triggerList)
				trigger.resume();
			_triggerList.clear();
			_lastMessage=null;
		}
		catch(IOException ioe)
		{
			ioe.printStackTrace();
		}
	}

	@Override
	public String getBindURI()
	{
		return _bindURI;
	}

	public void setBindURI(String uri)
	{
		_bindURI=uri;
	}
}
