package com.jxml.quick.util.qdmlRoot;
import java.io.*;
import java.util.*;
import org.xml.sax.*;
import com.jxml.quick.*;
import com.jxml.quick.ocm.*;
import com.jxml.protocol.*;
//import net.sourceforge.jxunit.*;
import com.jxml.quick.config.Item;

public class SetRoot implements /*JXTestStep,*/ Item
{
	/**
	 * This method can be invoked by config.<br>
	 * in - the (required) property naming the QDML document to be updated<br>
	 * root - the (required) property naming the root element<br>
	 * out - the (optional) property naming the output file.
	 */
 	public void eval(Map properties, List args, ClassLoader cl)
		throws Exception
	{
		String in=properties.get("in").toString();
		String out=properties.get("out").toString();
		String root=properties.get("root").toString();
		String schemaName="classpath:///OCMdom.qiml";
		QDoc schema=Quick.parseSchema(schemaName);
		QDoc doc=Quick.parse(schema,in);
		OCMelement element=(OCMelement)doc.getRoot();
		OCMattribute attribute=new OCMattribute("root",root);
		element.addAttribute(attribute);
		if("".equals(out))
			System.out.println(Quick.express(doc));
		else
			Quick.express(doc,out);
	}

/*
	 * This method can be invoked from JXUnit to set the root element in a qdml file.<br>
	 * qdml - the property containg the QDML document to be updated<br>
	 * root - the property naming the root element
	
	public void eval(JXTestCase testCase)
		throws Throwable
	{
		JXProperties properties=testCase.getProperties();
		String input=properties.getString("qdml");
		String root=properties.getString("root");
		String output=update(input,root);
		properties.put("qdml",output);
	}
*/

	public String update(String input, String root)
		throws Throwable
	{
		String schemaName="classpath:///OCMdom.qiml";
		QDoc schema=Quick.parseSchema(schemaName);
		QDoc doc=Quick.parseString(schema,input);
		OCMelement element=(OCMelement)doc.getRoot();
		OCMattribute attribute=new OCMattribute("root",root);
		element.addAttribute(attribute);
		return Quick.express(doc);
	}

	/**
	 * Sets the root attribute in a qdml file.<br>
	 * args[0] - The qdml input file.<br>
	 * args[1] - The root element name.<br>
	 * args[2] - The qdml output file. (optional)<br>
	 */
	public static void main(String args[])
	{
	try
	    {
		// Include classpath protocol
		Protocol.addJXMLProtocolPackage();

		String schemaName="classpath:///OCMdom.qiml";
		QDoc schema=Quick.parseSchema(schemaName);
		QDoc doc=Quick.parse(schema,args[0]);
		OCMelement element=(OCMelement)doc.getRoot();
		OCMattribute attribute=new OCMattribute("root",args[1]);
		element.addAttribute(attribute);
		int sargs=args.length;
		if(sargs>2)
			Quick.express(doc,args[2]);
		else
			System.out.println(Quick.express(doc));
	    } 
	catch (Exception e)
	    {
		QPE.display(e);
	    }
	}
}