/*
 * $Header: /home/cvspublic/jakarta-slide/src/stores/org/apache/slide/store/impl/rdbms/expression/RDBMSCompareExpression.java,v 1.10 2005/06/15 10:18:27 unico Exp $
 * $Revision: 1.10 $
 * $Date: 2005/06/15 10:18:27 $
 *
 * ====================================================================
 *
 * Copyright 1999-2004 The Apache Software Foundation 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.apache.slide.store.impl.rdbms.expression;

import java.util.HashMap;
import java.util.Iterator;

import org.apache.slide.content.NodeProperty.NamespaceCache;
import org.apache.slide.search.SearchException;
import org.apache.slide.search.basic.IBasicResultSet;
import org.apache.slide.search.basic.Literals;
import org.jdom.Element;

/**
 */
public class RDBMSCompareExpression extends RDBMSExpression {

    static final HashMap COMPARE_OPERATORS = new HashMap(11);
    static {
        COMPARE_OPERATORS.put(Literals.EQ, "=");
        COMPARE_OPERATORS.put(Literals.GT, ">");
        COMPARE_OPERATORS.put(Literals.GTE, ">=");
        COMPARE_OPERATORS.put(Literals.LT, "<");
        COMPARE_OPERATORS.put(Literals.LTE, "<=");
        COMPARE_OPERATORS.put(Literals.NOT_EQ, "<>");
        COMPARE_OPERATORS.put(Literals.NOT_GT, COMPARE_OPERATORS.get("LTE"));
        COMPARE_OPERATORS.put(Literals.NOT_GTE, COMPARE_OPERATORS.get("LT"));
        COMPARE_OPERATORS.put(Literals.NOT_LT, COMPARE_OPERATORS.get("GTE"));
        COMPARE_OPERATORS.put(Literals.NOT_LTE, COMPARE_OPERATORS.get("GT"));
    }
    
    protected final Element _element;
    protected int _tableIndex = -1;
    private Element _property;

    public RDBMSCompareExpression(Element element, RDBMSQueryContext context) {
        super(context);
        _element = element;
    }

    public IBasicResultSet execute() throws SearchException {
        return compile(null);
    }
    
    protected IBasicResultSet compile(RDBMSMergeExpression expression) {
        if (expression != null && expression.getName().equals(Literals.OR)) {
            Iterator iter = expression.getRDBMSExpressions().iterator();
            while (iter.hasNext()) {
                final RDBMSExpression e = (RDBMSExpression) iter.next();
                if (e instanceof RDBMSCompareExpression) {
                    _tableIndex = ((RDBMSCompareExpression) e).getTableIndex();
                    if (_tableIndex != -1) {
                        break;
                    }
                }
            }
        }
        if (_tableIndex == -1) {
            _tableIndex = _context.joins().size();
        }
        _context.joins().add(join());
        _context.criteria().add(compile());
        final String selectKey = getPropertyNamespace() + getPropertyName();
        _context.selects().put(selectKey, select());
        return _context.results();
    }

    protected String compile() {
        Element literal = _element.getChild(Literals.LITERAL, NamespaceCache.DEFAULT_NAMESPACE);
        return "(p" + _tableIndex + ".PROPERTY_NAME = '" + getPropertyName() + "' AND " +
                "p" + _tableIndex + ".PROPERTY_NAMESPACE = '" + getPropertyNamespace() + "' AND " +
                "p" + _tableIndex + ".PROPERTY_VALUE " + COMPARE_OPERATORS.get(_element.getName()) 
                + " '" + escapeLiteral(literal.getTextNormalize()) + "')";
    }

    protected String join() {
        return "inner join PROPERTIES p" + _tableIndex + " on p" + _tableIndex + ".VERSION_ID = vh.VERSION_ID";
    }

    protected String select() {
        // TODO: qualify alias
        return "p" + _tableIndex + ".PROPERTY_VALUE AS " 
            + RDBMSExpressionFactory.propertyToAlias(getPropertyName());
    }

    protected int getTableIndex() {
        return _tableIndex;
    }

    protected Element getProperty() {
        if (_property == null) {
            _property = (Element) _element.getChild(Literals.PROP, 
                    NamespaceCache.DEFAULT_NAMESPACE).getChildren().get(0);
        }
        return _property;
    }
    
    protected String getPropertyName() {
        return getProperty().getName();
    }
    
    protected String getPropertyNamespace() {
        return getProperty().getNamespaceURI();
    }

    /**
     * Single quotes need to be escaped.
     */
    protected static String escapeLiteral(String literal) {
        StringBuffer sb = new StringBuffer(literal.length() + 3);
        for (int i = 0, l = literal.length(); i < l; i++) {
            char c = literal.charAt(i);
            if (c == '\'') {
                sb.append("''");
            }
            else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

}