/*
 *  Copyright (C) 2006  Takashi Kasuya <kasuya@sfc.keio.ac.jp>
 *
 * This library is free software; you can redistribute it and/or
 *　modify it under the terms of the GNU Lesser General Public
 *　License as published by the Free Software Foundation; either
 *　version 2.1 of the License, or (at your option) any later version.
 *　This library is distributed in the hope that it will be useful,
 *　but WITHOUT ANY WARRANTY; without even the implied warranty of
 *　MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *　Lesser General Public License for more details.
 *
 *　You should have received a copy of the GNU Lesser General Public
 *　License along with this library; if not, write to the Free Software
 *　Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

package jp.ac.naka.ec.sip;

import gov.nist.javax.sip.header.From;

import javax.sip.RequestEvent;
import javax.sip.address.SipURI;
import javax.sip.header.ContentTypeHeader;
import javax.sip.header.FromHeader;
import javax.sip.header.ToHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import javax.xml.parsers.ParserConfigurationException;

import jp.ac.naka.ec.EntityCollaborator;
import jp.ac.naka.ec.entity.AbstractEntity;
import jp.ac.naka.ec.entity.Entity;
import jp.ac.naka.ec.entity.EntityContainer;
import jp.ac.naka.ec.entity.EntityContainerImpl;
import jp.ac.naka.ec.entity.EntityEvent;
import jp.ac.naka.ec.entity.EntityImpl;
import jp.ac.naka.ec.sip.pidf.PIDFParserImpl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.SAXException;

/**
 * @author Takashi Kasuya
 * 
 */
class MessageDelegate implements MethodDelegate {
	private static Log logger = LogFactory.getLog(MessageDelegate.class);
	PIDFParserImpl parser = PIDFParserImpl.getInatance();
	private static SipCore core;
	private static EntityContainer container;
	
	public MessageDelegate() throws ParserConfigurationException, SAXException {
		core = SipCore.getInstance();
		container = EntityContainerImpl.getInstance();
	}

	/*
	 * (non-Javadoc)
	 * @see jp.ac.naka.ec.sip.MethodDelegate#forward(javax.sip.RequestEvent)
	 */
	public boolean forward(RequestEvent evt) {
		
		Request req = evt.getRequest();
		byte[] content = req.getRawContent();
		ToHeader to = (ToHeader) req.getHeader(ToHeader.NAME);
		SipURI toUri = (SipURI) to.getAddress().getURI();
		
		//ContactHeader from = (ContactHeader)req.getHeader(ContactHeader.NAME);
		
		FromHeader from = (FromHeader) req.getHeader(From.NAME);
		SipURI fromUri = (SipURI) from.getAddress().getURI();
		ContentTypeHeader content_type = (ContentTypeHeader) req
				.getHeader(ContentTypeHeader.NAME);
		logger.info("From : " + fromUri);
		System.out.println("From : " + fromUri);
		try {
			Entity source = EntityContainerImpl.getInstance().getEntity(fromUri.toString());
			if (source ==null) {
				source = new EntityImpl(fromUri);
				source.setLocal(false);
			}
			Entity target = (AbstractEntity)container.getEntity(toUri.toString());
			// Targetのユーザ名でEntityの探索
			if (target == null) {
				String user = toUri.getUser();
				Entity[] result = EntityCollaborator.getInstance().searchEntities(user);
				if (result.length != 0)
					target = result[0];
			}
			if (target == null) 
				throw new NullPointerException(toUri + " is null!");
			String message = new String(content, "UTF-8");
			EntityEvent e = null;
			if (content_type.getContentType().equals("text")
					&& (content_type.getContentSubType().equals("plain") || content_type.getContentSubType().equals("html"))) {
				logger.info(message);
				e = new EntityEvent(message, target, source);
				// 200 OK
				core.sendResponse(Response.OK, req);
				((AbstractEntity)target).handleEvent(e);
			} 
			// XLite仕様
			else if (content_type.getContentType().equals("application")
					&& content_type.getContentSubType().equals("im-iscomposing+xml")) {
				core.sendResponse(Response.OK, req);
				//message = message.replaceAll("goober", "text/plain");
				//core.sendRequest(message, source, target, Request.MESSAGE);
			}
			
			else {
				throw new IllegalArgumentException(
						"Can not handle ContentType :" + content_type);
			}
			
			
		} catch (Exception e) {
			logger.warn("Error occures while processing SIP Message :", e);
			return false;
		}
		return true;
	}
}
