/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.core.oxm.adapter;

import java.util.ArrayList;
import java.util.List;

import nuts.core.beans.BeanHandler;
import nuts.core.beans.BeanHandlerFactory;
import nuts.core.beans.PropertyUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;

/**
 * This class is the most general type of adapter, utilizing reflective
 * introspection to present a DOM view of all of the public properties of its
 * value. For example, a property returning a JavaBean such as:
 * 
 * <pre>
 * public Person getMyPerson() { ... }
 * ...
 * class Person {
 *      public String getFirstName();
 *      public String getLastName();
 * }
 * </pre>
 * 
 * would be rendered as: <myPerson> <firstName>...</firstName>
 * <lastName>...</lastName> </myPerson>
 */
public class JavaBeanElementAdapter extends AbstractElementAdapter {
	private static Log log = LogFactory.getLog(JavaBeanElementAdapter.class);

	private List<Node> children;
	
	/**
	 * Constructors
	 */
	public JavaBeanElementAdapter() {
	}

	public JavaBeanElementAdapter(AdapterFactory adapterFactory, NodeAdapter parent,
			String propertyName, Object value) {
		setContext(adapterFactory, parent, propertyName, value);
	}

	public void setAttribute(String name, String value) throws DOMException {
		Attr a = getAttributeNode(name);
		if (a == null) {
			throw new IllegalArgumentException("Invalid attribute name: " + name);
		}
		a.setValue(value);

		PropertyUtils.setProperty(getPropertyValue(), name, value);
	}


	@Override
	protected List<Node> buildAttrAdapters() {
		List<Node> childs = buildPropertyAdapters();
		List<Node> attrs = new ArrayList<Node>();
		for (Node n : childs) {
			if (n.getNodeType() == Node.ATTRIBUTE_NODE) {
				attrs.add(n);
			}
		}
		return attrs;
	}

	@Override
	protected List<Node> buildChildAdapters() {
		List<Node> childs = buildPropertyAdapters();
		List<Node> nodes = new ArrayList<Node>();
		for (Node n : childs) {
			if (n.getNodeType() != Node.ATTRIBUTE_NODE) {
				nodes.add(n);
			}
		}
		return nodes;
	}

	@SuppressWarnings("unchecked")
	protected List<Node> buildPropertyAdapters() {
		if (children != null) {
			return children;
		}
		
		children = new ArrayList<Node>();
		Object pv = getPropertyValue();
		Class type = pv.getClass();

		BeanHandler bh = BeanHandlerFactory.getInstance().getBeanHandler(type);
		for (String cn : bh.getReadPropertyNames(pv)) {
			if ("class".equals(cn)) {
				continue;
			}

			Object cv;
			try {
				cv = bh.getBeanValue(pv, cn);
			}
			catch (Exception e) {
				log.warn("Cannot access bean property: " + cn, e);
				continue;
			}

			Node child = getAdapterFactory().adaptNodeOrAttr(this, cn, cv);
			if (child != null) {
				children.add(child);
			}
		}
		
		return children;
	}
}
