/*
 *  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 java.util.ArrayList;
import java.util.List;

import javax.sip.RequestEvent;
import javax.sip.address.SipURI;

import jp.ac.naka.ec.EventDispatcher;
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.EntityImpl;
import jp.ac.naka.ec.entity.EntityType;
import jp.ac.naka.ec.sip.pidf.PIDFData;
import jp.ac.naka.ec.sip.pidf.Tuple;

/**
 * 
 * @author Takashi Kasuya
 *
 */
abstract class MethodDelegate {

	EventDispatcher dispatcher;
	SipCore core ;
	
	/**
	 * 
	 * @param evt
	 * @return
	 */
	public abstract boolean forward(final RequestEvent evt);
	
	/**
	 * PIDF
	 * 
	 * @param data
	 * @return
	 */
	protected Entity[] makeEntitiesFromPIDF(PIDFData data) {
		SipURI uri = (SipURI) data.getURI();
		String name = uri.getUser();
		EntityContainer con = new EntityContainerImpl();
		con.setName(name);
		con.setURI(uri);
		con.setLocal(false);
		if (data.getLocation() != null)
			con.setLocation(data.getLocation());
		List<Tuple> tuples = data.getTuples();
		List<Entity> entities = new ArrayList<Entity>();
		entities.add(con);
		for (Tuple tuple : tuples) {

			EntityType type = EntityType.valueOf((String) tuple
					.getExtension("type"));
			Entity entity;
			// 同じホストのものは避ける
			String temp = (String) tuple.getExtension("uri");
			
			if (type == EntityType.CONTAINER) {
				entity  = new EntityContainerImpl();
			} else {
				entity = new EntityImpl();
			}
			entity.setLocal(false);
			entity.setParent(con);
			entity.setName((String) tuple.getExtension("name"));
			entity.setTupleId(tuple.id);
			entity.setEntityType(type);
			entity.setAlive(tuple.isAlived());
			if (temp != null) {
				SipURI e_uri = core.createURI(temp);
				if (e_uri != null)
					entity.setURI(e_uri);
			}
			entities.add(entity);
		}
		if (tuples.size() == 0) {
			return null;
		}
		
		Entity[] temp = new Entity[entities.size()];
		return entities.toArray(temp);
	}
}