/* 
 * 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 java.util.Map;

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

/**
 * For inputting from XmlRpc.
 */
public class XmlRpcInputAdapter 
	implements ProvIterator
{
	ParamIterator pi;

	public XmlRpcInputAdapter(ParamIterator pi) {
		this.pi = pi;
	}

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

	static ProvEntity toEntity(Map map) 
		throws ProvException, XmlRpcException
	{
		String obj = (String)map.get("object");
		if (obj == null)
			throw new ProvException("null entity in " + map);
		if (obj.equals(ProvResult.class.getName())) {
			return new ProvResult((String)map.get("message"),
				toEntity((Map)map.get("entity"))); 
		}
		if (obj.equals(Subscriber.class.getName())) {
			return new SubscriberImpl((String)map.get("name"), (String)map.get("password"));
		}
		if (obj.equals(SubscriberSearch.class.getName())) {
			return new SubscriberSearchImpl((String)map.get("matchName"));
		}
		throw new ProvException("unknown entity in " + map);
	}

	static ProvEntity toEntity(ParamIterator o) 
		throws ProvException, XmlRpcException
	{
		java.util.Map map = net.noderunner.xmlrpc.MapAdapter.toMap(o);
		return toEntity(map);
	}

	/**
	 * Returns a MapAdapter per object.
	 */
	public ProvEntity next() 
		throws ProvException
	{
		try {
			Object o = pi.next();
			if (o instanceof ParamIterator) {
				return toEntity((ParamIterator)o);
			}
			throw new ProvException("Unknown underlying object " + o);
		} catch (XmlRpcException xre) {
			throw new ProvException("next() failed", xre);
		}
	}

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