package gov.va.med.cds.mediator.xml.transform.saxonextensions;

import java.io.StringReader;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;

import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.lib.NamespaceConstant;
import net.sf.saxon.om.DocumentInfo;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.SequenceType;
import net.sf.saxon.value.StringValue;


public class SurveyParseExtFunc extends ExtensionFunctionDefinition {

	
	private static final long serialVersionUID = 6633026012953507284L;
	private static final StructuredQName qName = new StructuredQName("", NamespaceConstant.SAXON, "parse-survey");
	
	@Override
	public StructuredQName getFunctionQName() {
		
		return qName;
	}

	@Override
	public SequenceType[] getArgumentTypes() {
		
		return new SequenceType[]{SequenceType.STRING_SEQUENCE};

	}

	@Override
	public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) {
		
		return SequenceType.NODE_SEQUENCE;
	}
	

	@Override
	public ExtensionFunctionCall makeCallExpression() {
		
		return new SurveyParseCall();
	}
	
	private static class SurveyParseCall extends ExtensionFunctionCall{

		
		@Override
		public Sequence call(XPathContext context, Sequence[] arguments)
				throws XPathException {
			
		
			Sequence seq= arguments[0];
			String xml = ((StringValue)seq.head()).getStringValue();
			
			if(xml == null){
				return seq;
			}
			
			Source source = new StreamSource(new StringReader(xml));
			DocumentInfo docInfo = context.getConfiguration().buildDocument(source);
		
			return docInfo;	
			
		}

	}

}
