package com.jxml.quick.qmap;
import com.jxml.quick.*;
import com.jxml.quick.access.*;
import com.jxml.quick.tf.*;
import java.util.*;
import java.beans.*;

public class QMapPropertyAccess extends QPropertyAccess
{
    public boolean readable(QTargetFactory parentFactory, QContext context)
	throws QPE
    {
	return true;
    }

    protected boolean validProperty(PropertyDescriptor pd)
    {
	Class propertyType=pd.getPropertyType();
	return QMapFieldAccess.mapClass.isAssignableFrom(propertyType)
	    && pd.getReadMethod()!=null;
    }
    public final QIterator createIterator()
    {
	return new QMapIterator();
    }

    protected Map getMap(QTargetFactory parentFactory, Object parent, QContext context)
	throws QPE
    {
	return (Map)super.get(parentFactory,parent,context);
    }

    protected Map getNonNullMap(QTargetFactory parentFactory, Object parent, QContext context)
	throws QPE
    {
	Map result = getMap(parentFactory,parent, context);

	if (result == null)
	    context.throwPE("Map property \"" + property + "\" is null");
	return result;
    }

    public final void setIteratorParent(QIterator it, 
					Object parent, 
					QTargetFactory parentFactory,
					QContext context)
	throws QPE
    {
	setPD(parentFactory,context);
	((QMapIterator)it).setMap(getMap(parentFactory,parent,context));
    }

    public boolean writeable(QTargetFactory parentFactory, QContext context)
	throws QPE
    {
	return true;
    }

    public final void add(Object parent, 
			  QTargetFactory parentFactory,
			  Object child, 
			  QContext context)
	throws QPE
    {
	if (!(child instanceof QKeyed))
	    context.throwPE("Child must be QKeyed, not "+child.getClass().getName());
	setPD(parentFactory,context);
	Map map=getNonNullMap(parentFactory,parent,context);
	QKeyed qk=(QKeyed)child;
	qk.attach(map);
    }
}
