

package gov.va.med.cds.persistence.hibernate.interceptor;


import java.io.Serializable;

import org.springframework.beans.factory.annotation.Required;


public class XmlTypeExtractQueryInterceptor
    extends
        DefaultInterceptor
    implements
        Serializable
{

    /**
     * 
     */
    private static final long serialVersionUID = -918760231184746966L;

    // The XPath expression to use in the XMLTYPE.EXTRACT
    private String extractExpression;
    // The Namespace to use for the XPath expression.
    private String extractExpressionNamespace;
    // The parameter in the query to replace with the extract expression
    private String xPathParameterName;
    // The namespace parameter name to replace in the query with the namespace
    private String xPathNamespaceParameterName;


    public void setExtractExpression( String extractExpression )
    {
        this.extractExpression = escapeExpression( extractExpression );
    }
    
    public void setExtractExpressionNamespace( String extractExpressionNamespace )
    {
        this.extractExpressionNamespace = escapeExpression(extractExpressionNamespace);
    }

    @Required
    public void setxPathParameterName( String xPathParameterName )
    {
        this.xPathParameterName = xPathParameterName;
    }
    
    @Required
    public void setxPathNamespaceParameterName( String xPathNamespaceParameterName )
    {
        this.xPathNamespaceParameterName = xPathNamespaceParameterName;
    }


    private String escapeExpression( String expression )
    {
        // Escape quotes in the Oracle Query
        return expression.replaceAll( "'", "''" );
    }


    @Override
    public String onPrepareStatement( String sql )
    {
        // Move to ANTLR SQL Parser
        if ( extractExpression != null && extractExpression.length() > 0 )
        {
            sql = sql.replaceFirst( this.xPathParameterName, this.extractExpression )
                     .replaceFirst( this.xPathNamespaceParameterName, this.extractExpressionNamespace );
        }

        return sql;
    }

}
