/*
 * JBoss, Home of Professional Open Source.
 * See the COPYRIGHT.txt file distributed with this work for information
 * regarding copyright ownership.  Some portions may be licensed
 * to Red Hat, Inc. under one or more contributor license agreements.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library 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
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * Modified by
 * @author  Data Virtuality GmbH
 * @date    $Date$
 *  
 */
// https://issues.jboss.org/browse/TEIID-2141
// https://issues.jboss.org/browse/TEIID-3030
// https://issues.jboss.org/browse/TEIID-5233
package org.teiid.query.xquery.saxon;

import com.datavirtuality.dv.core.interfaces.DVCaller;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Map;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stax.StAXSource;

import net.sf.saxon.Configuration;
import net.sf.saxon.event.FilterFactory;
import net.sf.saxon.event.ProxyReceiver;
import net.sf.saxon.event.Receiver;
import net.sf.saxon.expr.JPConverter;
import net.sf.saxon.lib.AugmentedSource;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.om.TreeInfo;
import net.sf.saxon.option.xom.XOMDocumentWrapper;
import net.sf.saxon.query.DynamicQueryContext;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.AtomicValue;
import net.sf.saxon.value.DateTimeValue;
import net.sf.saxon.value.DateValue;
import net.sf.saxon.value.DayTimeDurationValue;
import net.sf.saxon.value.HexBinaryValue;
import net.sf.saxon.value.TimeValue;
import nu.xom.Builder;
import nu.xom.DocType;
import nu.xom.Element;
import nu.xom.Node;
import nu.xom.NodeFactory;
import nu.xom.Nodes;
import nu.xom.ParsingException;
import nux.xom.xquery.StreamingPathFilter;
import nux.xom.xquery.StreamingTransform;

import org.teiid.core.TeiidComponentException;
import org.teiid.core.TeiidProcessingException;
import org.teiid.core.TeiidRuntimeException;
import org.teiid.core.types.BinaryType;
import org.teiid.core.types.XMLType;
import org.teiid.logging.LogConstants;
import org.teiid.logging.LogManager;
import org.teiid.logging.MessageLevel;
import org.teiid.query.QueryPlugin;
import org.teiid.query.function.source.XMLSystemFunctions;
import org.teiid.query.processor.relational.RelationalNode;
import org.teiid.query.util.CommandContext;
import org.teiid.query.xquery.saxon.SaxonXQueryExpression.RowProcessor;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * Used to isolate the xom/nux dependency and to better isolate the saxon processing logic.
 */
public class XQueryEvaluator {
	
	private static Nodes NONE = new Nodes(); 
	private static InputStream FAKE_IS = new InputStream() {

		@Override
		public int read() throws IOException {
			return 0;
		}
	};

	public static SaxonXQueryExpression.Result evaluateXQuery(final SaxonXQueryExpression xquery, Object context, Map<String, Object> parameterValues, final RowProcessor processor, CommandContext commandContext) throws TeiidProcessingException, TeiidComponentException {
	    DynamicQueryContext dynamicContext = new DynamicQueryContext(xquery.config);
	
	    SaxonXQueryExpression.Result result = new SaxonXQueryExpression.Result();
	    try {
	    	for (Map.Entry<String, Object> entry : parameterValues.entrySet()) {
	        try {
		            Object value = entry.getValue();
				    Sequence s = null;
		            if(value instanceof SQLXML) {                    
		            	value = XMLSystemFunctions.convertToSource(value);
		            	result.sources.add((Source)value);
					    Source source = wrapStax((Source) value);
					    s = xquery.config.buildDocumentTree(source).getRootNode();
		            } else if (value instanceof java.util.Date) {
					    s = XQueryEvaluator.convertToAtomicValue(value);
		            } else if (value instanceof BinaryType) {
					    s = new HexBinaryValue(((BinaryType) value).getBytesDirect());
		            }
				    dynamicContext.setParameter(StructuredQName.fromClarkName(entry.getKey()), s);
	        } catch (TransformerException e) {
				    throw new TeiidProcessingException(QueryPlugin.Event.TEIID30148, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30148, entry.getKey()));
	        }
		    }
	        if (context != null) {
	        	Source source = XMLSystemFunctions.convertToSource(context);
	        	result.sources.add(source);
		        source = wrapStax(source);
	            if (xquery.contextRoot != null) {
	            	//create our own filter as this logic is not provided in the free saxon
	                AugmentedSource sourceInput = AugmentedSource.makeAugmentedSource(source);
		            sourceInput.addFilter(new FilterFactory() {
					    @Override
			            public ProxyReceiver makeFilter(Receiver arg0) {
				            return new PathMapFilter(xquery.contextRoot, arg0);
				        }
			        });
		            // EXTENSION
		            // ISSUE: DVCORE-2478
		            // SOLUTION: added check of SUPPORT_DTD parameter to turn on/off DTD validation
		            // FIXED BY: Dmitry Pogorelov
		            // DATE: 2015.03.12
		            //source = sourceInput;
		            final XMLType xmlType = context instanceof XMLType ? (XMLType)context : null;
		            sourceInput.setEntityResolver(new EntityResolver() {
			            @Override
			            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
				            if (xmlType != null && systemId.toLowerCase().indexOf((".dtd")) != -1) {
					            XMLInputFactory inputFactory = xmlType.getXmlInputFactory();
					            Boolean supportDTD = (Boolean)inputFactory.getProperty(XMLInputFactory.SUPPORT_DTD);
					            if (!supportDTD) {
						            return new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
					            }
				            }
				            return null;
			            }
		            });
		            source = sourceInput;
		            // END EXTENSION
	
	            	//use streamable processing instead
	                if (xquery.streamingPath != null && processor != null) {
	                	if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
	                		LogManager.logDetail(LogConstants.CTX_DQP, "Using stream processing for evaluation of", xquery.xQueryString); //$NON-NLS-1$
	                	}
	                	//set to non-blocking in case default expression evaluation blocks
	                	boolean isNonBlocking = commandContext.isNonBlocking();
						commandContext.setNonBlocking(true);
						
						final StreamingTransform myTransform = new StreamingTransform() {
							public Nodes transform(Element elem) {
								processor.processRow(XQueryEvaluator.wrap(elem, xquery.config));
								return NONE;
							}
						};

		                NodeFactory nodeFactory = (NodeFactory) DVCaller.call(171, processor);
						Builder builder = new Builder(new SaxonReader(xquery.config, sourceInput), false, 
								new StreamingPathFilter(xquery.streamingPath, xquery.namespaceMap).createNodeFactory(nodeFactory, myTransform));
						try {
							//the builder is hard wired to parse the source, but the api will throw an exception if the stream is null
							builder.build(FAKE_IS);
							return result;
						} catch (ParsingException e) {
						     if (e.getCause() instanceof TeiidRuntimeException) {
						         RelationalNode.unwrapException((TeiidRuntimeException)e.getCause());
							 }
							// EXTENSION
							// ISSUE: DVCORE-2478
							// SOLUTION: added showing of exception when parsing xml via saxon
							// FIXED BY: Dmitry Pogorelov
							// DATE: 2015.03.12
							//throw new TeiidProcessingException(QueryPlugin.Event.TEIID30151, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30151));
							throw new TeiidProcessingException(QueryPlugin.Event.TEIID30151, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30151, e));
							// END EXTENSION
						} catch (IOException e) {
							// EXTENSION
							// ISSUE: DVCORE-2478
							// SOLUTION: added showing of exception when parsing xml via saxon
							// FIXED BY: Dmitry Pogorelov
							// DATE: 2015.03.12
							//throw new TeiidProcessingException(QueryPlugin.Event.TEIID30151, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30151));
							throw new TeiidProcessingException(QueryPlugin.Event.TEIID30151, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30151, e));
							// END EXTENSION
						} finally {
							if (!isNonBlocking) {
								commandContext.setNonBlocking(false);
							}
						}
	                }
	            }
		        TreeInfo doc;
				try {
					doc = xquery.config.buildDocumentTree(source);
				} catch (XPathException e) {
					 // EXTENSION
					 // ISSUE: DVCORE-2478
					 // SOLUTION: added showing of exception when parsing xml via saxon
					 // FIXED BY: Dmitry Pogorelov
					 // DATE: 2015.03.12
					 //throw new TeiidProcessingException(QueryPlugin.Event.TEIID30151, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30151));
					 throw new TeiidProcessingException(QueryPlugin.Event.TEIID30151, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30151, e));
					 // END EXTENSION
				}
		        dynamicContext.setContextItem(doc.getRootNode());
	        }
	        try {
	        	result.iter = xquery.xQuery.iterator(dynamicContext);
	        	return result;
	        } catch (TransformerException e) {
	        	 throw new TeiidProcessingException(QueryPlugin.Event.TEIID30152, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30152));
	        }       
	    } finally {
	    	if (result.iter == null) {
	    		result.close();
	    	}
	    }
	}

	private static Source wrapStax(Source value) throws TeiidProcessingException {
		if (value instanceof StAXSource) {
			StAXSource staxSource = (StAXSource)value;
			if (staxSource.getXMLStreamReader() != null) {
				return staxSource;
			}
				try {
				return new StAXSource(new XMLEventStreamReader(staxSource.getXMLEventReader()));
				} catch (XMLStreamException e) {
					//should not happen as the StAXSource already peeked
					throw new TeiidProcessingException(e);
				}
			}
		return value;
	}

	/**
	 * Converts a xom node into something readable by Saxon
	 * @param node
	 * @param config
	 * @return
	 */
	static NodeInfo wrap(Node node, Configuration config) {
		if (node == null) 
			throw new IllegalArgumentException(QueryPlugin.Util.gs(QueryPlugin.Event.DVCORE301197));
		if (node instanceof DocType)
			throw new IllegalArgumentException(QueryPlugin.Util.gs(QueryPlugin.Event.DVCORE301198));
		
		Node root = node;
		while (root.getParent() != null) {
			root = root.getParent();
		}
	
		XOMDocumentWrapper docWrapper = new XOMDocumentWrapper(root, config);
		
		return docWrapper.wrap(node);
	}

	public static AtomicValue convertToAtomicValue(Object value) throws TransformerException {
		if (value instanceof java.util.Date) { //special handling for time types
			java.util.Date d = (java.util.Date)value;
			DateTimeValue tdv = DateTimeValue.fromJavaDate(d);
			if (value instanceof Date) {
				value = new DateValue(tdv.getYear(), tdv.getMonth(), tdv.getDay(), tdv.getTimezoneInMinutes(), true);
			} else if (value instanceof Time) {
				value = new TimeValue(tdv.getHour(), tdv.getMinute(), tdv.getSecond(), tdv.getMicrosecond(), tdv.getTimezoneInMinutes());
			} else if (value instanceof Timestamp) {
				Timestamp ts = (Timestamp)value;
				value = tdv.add(DayTimeDurationValue.fromMicroseconds(ts.getNanos() / 1000));
}
			return (AtomicValue)value;
		}
		JPConverter converter = JPConverter.allocate(value.getClass(), null, null);
		return (AtomicValue)converter.convert(value, null);
	}

}
