/*
 * 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 com.facebook.presto.sql.planner;

import com.facebook.presto.sql.analyzer.Field;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.sql.tree.QualifiedNameReference;
import com.facebook.presto.spi.type.Type;
import com.google.common.base.Preconditions;

import java.util.HashMap;
import java.util.Map;

import static java.util.Locale.ENGLISH;

public class SymbolAllocator
{
    private final Map<Symbol, Type> symbols = new HashMap<>();

    public Symbol newSymbol(String nameHint, Type type)
    {
        return newSymbol(nameHint, type, null);
    }

    public Symbol newSymbol(String nameHint, Type type, String suffix)
    {
        Preconditions.checkNotNull(nameHint, "name is null");

        // TODO: workaround for the fact that QualifiedName lowercases parts
        nameHint = nameHint.toLowerCase(ENGLISH);

        if (nameHint.contains("_")) {
            nameHint = nameHint.substring(0, nameHint.indexOf("_"));
        }

        String unique = nameHint;

        if (suffix != null) {
            unique = unique + "$" + suffix;
        }

        int id = 1;
        while (symbols.containsKey(new Symbol(unique))) {
            unique = nameHint + "_" + id;
            id++;
        }

        Symbol symbol = new Symbol(unique);
        symbols.put(symbol, type);
        return symbol;
    }

    public Symbol newSymbol(Expression expression, Type type)
    {
        return newSymbol(expression, type, null);
    }

    public Symbol newSymbol(Expression expression, Type type, String suffix)
    {
        String nameHint = "expr";
        if (expression instanceof QualifiedNameReference) {
            nameHint = ((QualifiedNameReference) expression).getName().getSuffix();
        }
        else if (expression instanceof FunctionCall) {
            nameHint = ((FunctionCall) expression).getName().getSuffix();
        }

        return newSymbol(nameHint, type, suffix);
    }

    public Symbol newSymbol(Field field)
    {
        String nameHint = field.getName().or("field");
        return newSymbol(nameHint, field.getType());
    }

    public Map<Symbol, Type> getTypes()
    {
        return symbols;
    }
}

@@ -597,16 +597,58 @@
 anner;%0A%0A
+import com.facebook.presto.spi.type.Type;%0A
 import c
@@ -686,16 +686,16 @@
 .Field;%0A
-
 import c
@@ -848,50 +848,8 @@
 ce;%0A
-import com.facebook.presto.spi.type.Type;%0A
 impo
@@ -888,16 +888,58 @@
 ditions;
+%0Aimport com.google.common.primitives.Ints;
 %0A%0Aimport
@@ -1514,34 +1514,137 @@
     
-if (nameHint.contains(%22_%22)
+// don't strip the tail if the only _ is the first character%0A        int index = nameHint.lastIndexOf(%22_%22);%0A        if (index %3E 0
 ) %7B%0A
@@ -1651,32 +1651,35 @@
             
-nameHint
+String tail
  = nameHint.
@@ -1692,34 +1692,244 @@
 ing(
-0, nameHint.indexOf(%22_%22));
+index + 1);%0A%0A            // only strip if tail is numeric or _ is the last character%0A            if (Ints.tryParse(tail) != null %7C%7C index == nameHint.length() - 1) %7B%0A                nameHint = nameHint.substring(0, index);%0A            %7D
 %0A   

Improve heuristic for creating symbols from name hints