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

public class QMapFieldAccess extends QFieldAccess
{
    public static final Class mapClass;

    static
    {
	try
	    {
		mapClass=Class.forName("java.util.Map");
	    }
	catch (Exception ex)
	    {
		throw new Error(ex.toString());
	    }
    }

    protected void validateField(Field pd,QContext context)
	throws QPE
    {
	if (!mapClass.isAssignableFrom(pd.getType()))
	    context.throwPE("Not a map: "+pd.getName());
    }

    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 field \"" + field + "\" 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 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);
    }
}
