/*
 * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
 * license agreements.  See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.  Crate licenses
 * this file to you 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.
 *
 * However, if you have executed another commercial license agreement
 * with Crate these terms will supersede the license and you may use the
 * software solely pursuant to the terms of the relevant commercial agreement.
 */
package io.crate.analyze;

import io.crate.metadata.FunctionImplementation;
import io.crate.metadata.Functions;
import io.crate.metadata.ReferenceResolver;
import io.crate.operation.Input;
import io.crate.planner.RowGranularity;
import io.crate.planner.symbol.*;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * the normalizer does symbol normalization and reference resolving if possible
 * <p/>
 * E.g.:
 * The query
 * <p/>
 * and(true, eq(column_ref, 'someliteral'))
 * <p/>
 * will be changed to
 * <p/>
 * eq(column_ref, 'someliteral')
 */
public class EvaluatingNormalizer extends SymbolVisitor<Void, Symbol> {

    private final ESLogger logger = Loggers.getLogger(getClass());
    private final Functions functions;
    private final RowGranularity granularity;
    private final ReferenceResolver referenceResolver;

    public EvaluatingNormalizer(
            Functions functions, RowGranularity granularity, ReferenceResolver referenceResolver) {
        this.functions = functions;
        this.granularity = granularity;
        this.referenceResolver = referenceResolver;
    }

    @Override
    public Symbol visitFunction(Function function, Void context) {
        List<Symbol> newArgs = normalize(function.arguments());
        if (newArgs != function.arguments()) {
            function = new Function(function.info(), newArgs);
        }
        return normalizeFunctionSymbol(function);
    }

    @SuppressWarnings("unchecked")
    private Symbol normalizeFunctionSymbol(Function function) {
        FunctionImplementation impl = functions.get(function.info().ident());
        if (impl != null) {
            return impl.normalizeSymbol(function);
        }
        logger.warn(SymbolFormatter.format("No implementation found for function %s", function));
        return function;
    }

    @Override
    public Symbol visitReference(Reference symbol, Void context) {
        if (symbol.info().granularity().ordinal() > granularity.ordinal()) {
            return symbol;
        }

        Input input = (Input) referenceResolver.getImplementation(symbol.info().ident());
        if (input != null) {
            return Literal.forType(symbol.info().type(), input.value());
        }

        logger.warn(SymbolFormatter.format("Can't resolve reference %s", symbol));
        return symbol;
    }

    @Override
    protected Symbol visitSymbol(Symbol symbol, Void context) {
        return symbol;
    }

    public boolean evaluatesToFalse(@Nullable Symbol whereClause) {
        if (whereClause == null) {
            return false;
        }
        return (whereClause.symbolType() == SymbolType.NULL_LITERAL ||
                (whereClause.symbolType() == SymbolType.BOOLEAN_LITERAL &&
                        !((BooleanLiteral) whereClause).value()));

    }


    /**
     * return <code>true</code> if this function evaluates to <code>false</code> or <code>null</code>
     *
     * @param whereClause
     * @return false if whereClause evaluates to <code>false</code> or {@link io.crate.planner.symbol.Null}
     */
    public boolean evaluatesToFalse(@Nullable Function whereClause) {
        // no whereClause means match all
        if (whereClause == null) {
            return false;
        }
        return evaluatesToFalse(process(whereClause, null));
    }

    /**
     * Normalizes all symbols of a List. Does not return a new list if no changes occur.
     *
     * @param symbols the list to be normalized
     * @return a list with normalized symbols
     */
    public List<Symbol> normalize(List<Symbol> symbols) {
        if (symbols.size() > 0) {
            boolean changed = false;
            Symbol[] newArgs = new Symbol[symbols.size()];
            int i = 0;
            for (Symbol symbol : symbols) {
                Symbol newArg = normalize(symbol);
                changed = changed || newArg != symbol;
                newArgs[i++] = newArg;
            }
            if (changed) {
                return Arrays.asList(newArgs);
            }
        }
        return symbols;
    }

    /**
     * Normalizes all objects in given list
     *
     * @param candidates the list to be normalized
     * @return a list of normalized objects
     */
    public <T extends Normalizable<T>> List<T> normalizeObjects(List<T> candidates) {
        if (candidates.size() > 0) {
            boolean changed = false;
            List<T> newArgs = new ArrayList<T>(candidates.size());
            int i = 0;
            for (T symbol : candidates) {
                T newArg = symbol.normalize(this);
                changed = changed || newArg != symbol;
                newArgs.add(newArg);
            }
            if (changed) {
                return newArgs;
            }
        }
        return candidates;
    }


    /**
     * Normalizes all symbols of a List in place
     *
     * @param symbols the list to be normalized
     */
    public void normalizeInplace(@Nullable List<Symbol> symbols) {
        if (symbols != null){
            for (int i = 0; i < symbols.size(); i++) {
                symbols.set(i, normalize(symbols.get(i)));
            }
        }
    }

    public Symbol normalize(@Nullable Symbol symbol) {
        if (symbol == null) {
            return null;
        }
        return process(symbol, null);
    }

}

@@ -1414,36 +1414,8 @@
 le;%0A
-import java.util.ArrayList;%0A
 impo
@@ -1435,16 +1435,16 @@
 Arrays;%0A
+
 import j
@@ -3592,879 +3592,8 @@
  %7D%0A%0A
-    public boolean evaluatesToFalse(@Nullable Symbol whereClause) %7B%0A        if (whereClause == null) %7B%0A            return false;%0A        %7D%0A        return (whereClause.symbolType() == SymbolType.NULL_LITERAL %7C%7C%0A                (whereClause.symbolType() == SymbolType.BOOLEAN_LITERAL &&%0A                        !((BooleanLiteral) whereClause).value()));%0A%0A    %7D%0A%0A%0A    /**%0A     * return %3Ccode%3Etrue%3C/code%3E if this function evaluates to %3Ccode%3Efalse%3C/code%3E or %3Ccode%3Enull%3C/code%3E%0A     *%0A     * @param whereClause%0A     * @return false if whereClause evaluates to %3Ccode%3Efalse%3C/code%3E or %7B@link io.crate.planner.symbol.Null%7D%0A     */%0A    public boolean evaluatesToFalse(@Nullable Function whereClause) %7B%0A        // no whereClause means match all%0A        if (whereClause == null) %7B%0A            return false;%0A        %7D%0A        return evaluatesToFalse(process(whereClause, null));%0A    %7D%0A%0A
     
@@ -4334,744 +4334,15 @@
 ls;%0A
+
     %7D%0A%0A
-    /**%0A     * Normalizes all objects in given list%0A     *%0A     * @param candidates the list to be normalized%0A     * @return a list of normalized objects%0A     */%0A    public %3CT extends Normalizable%3CT%3E%3E List%3CT%3E normalizeObjects(List%3CT%3E candidates) %7B%0A        if (candidates.size() %3E 0) %7B%0A            boolean changed = false;%0A            List%3CT%3E newArgs = new ArrayList%3CT%3E(candidates.size());%0A            int i = 0;%0A            for (T symbol : candidates) %7B%0A                T newArg = symbol.normalize(this);%0A                changed = changed %7C%7C newArg != symbol;%0A                newArgs.add(newArg);%0A            %7D%0A            if (changed) %7B%0A                return newArgs;%0A            %7D%0A        %7D%0A        return candidates;%0A    %7D%0A%0A%0A
     

remove unused code from EvaluatingNormalizer