/* 
 * E-XML Library:  For XML, XML-RPC, HTTP, and related.
 * Copyright (C) 2002-2008  Elias Ross
 * 
 * genman@noderunner.net
 * http://noderunner.net/~genman
 * 
 * 1025 NE 73RD ST
 * SEATTLE WA 98115
 * USA
 *
 * 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.
 * 
 * $Id$
 */

package net.noderunner.xmlrpc.example;

import net.noderunner.xmlrpc.ParamIterator;
import net.noderunner.xmlrpc.XmlRpcException;

/**
 * For outputting to XmlRpc.
 */
public class XmlRpcOutputAdapter 
	implements ParamIterator
{
	ProvIterator pi;

	public XmlRpcOutputAdapter(ProvIterator pi) {
		this.pi = pi;
	}

	/**
	 * Returns ARRAY_ITERATOR as its type.
	 */
	public int getIteratorType() {
		return ARRAY_ITERATOR;
	}

	public boolean hasNext() 
		throws XmlRpcException
	{
		try {
			return pi.hasNext();
		} catch (ProvException pe) {
			throw new XmlRpcException(0, "hasNext() failed", pe);
		}
	}

	static ParamIterator toParamIterator(Object o) 
		throws ProvException
	{
		java.util.Map m = new java.util.HashMap();
		if (o instanceof Subscriber) {
			Subscriber u = (Subscriber)o;
			m.put("object", Subscriber.class.getName());
			m.put("name", u.getName());
			m.put("password", u.getPassword());
		} else
		if (o instanceof SubscriberSearch) {
			SubscriberSearch ss = (SubscriberSearch)o;
			m.put("object", SubscriberSearch.class.getName());
			m.put("matchName", ss.getMatchName());
		} else
		if (o instanceof ProvResult) {
			ProvResult p = (ProvResult)o;
			m.put("object", ProvResult.class.getName());
			m.put("message", p.getMessage());
			m.put("entity", toParamIterator(p.getEntity()));
		} else {
			throw new ProvException("Unknown underlying object " + o);
		}
		return new net.noderunner.xmlrpc.MapAdapter(m);
	}

	/**
	 * Returns a MapAdapter per object.
	 */
	public Object next() 
		throws XmlRpcException
	{
		try {
			Object o = pi.next();
			return toParamIterator(o);
		} catch (ProvException pe) {
			throw new XmlRpcException(0, "next() failed", pe);
		}
	}

	public void close() 
		throws XmlRpcException
	{
		try {
			pi.close();
		} catch (ProvException pe) {
			throw new XmlRpcException(0, "close() failed", pe);
		}
	}
}
