/*
 * 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.gen;

import com.facebook.presto.sql.relational.CallExpression;
import com.facebook.presto.sql.relational.ConstantExpression;
import com.facebook.presto.sql.relational.InputReferenceExpression;
import com.facebook.presto.sql.relational.RowExpression;
import com.facebook.presto.sql.relational.RowExpressionVisitor;
import com.google.common.collect.ImmutableList;

import java.util.List;

import static com.facebook.presto.sql.relational.Signatures.TRY;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.getOnlyElement;

public class TryExpressionExtractor
{
    private TryExpressionExtractor()
    {
    }

    public static List<CallExpression> extractTryExpressions(RowExpression expression)
    {
        Visitor tryOrLambdaExtractor = new Visitor();
        expression.accept(tryOrLambdaExtractor, new Context());
        return tryOrLambdaExtractor.getTryExpressionsPreOrder();
    }

    private static class Visitor
            implements RowExpressionVisitor<Context, Void>
    {
        private final ImmutableList.Builder<CallExpression> tryExpressions = ImmutableList.builder();

        @Override
        public Void visitInputReference(InputReferenceExpression node, Context context)
        {
            // TODO: change such that CallExpressions only capture the inputs they actually depend on
            return null;
        }

        @Override
        public Void visitCall(CallExpression call, Context context)
        {
            if (call.getSignature().getName().equals(TRY)) {
                checkState(call.getArguments().size() == 1, "try call expressions must have a single argument");
                checkState(getOnlyElement(call.getArguments()) instanceof CallExpression, "try call expression argument must be a call expression");

                tryExpressions.add((CallExpression) getOnlyElement(call.getArguments()));
            }

            for (RowExpression rowExpression : call.getArguments()) {
                rowExpression.accept(this, null);
            }

            return null;
        }

        @Override
        public Void visitConstant(ConstantExpression literal, Context context)
        {
            return null;
        }

        public List<CallExpression> getTryExpressionsPreOrder()
        {
            return tryExpressions.build().reverse();
        }
    }

    private static class Context
    {
    }
}

@@ -1519,26 +1519,27 @@
 ExpressionsP
-re
+ost
 Order();%0A   
@@ -2109,12 +2109,24 @@
     
-if (
+boolean isTry = 
 call
@@ -2162,16 +2162,39 @@
 als(TRY)
+;%0A            if (isTry
 ) %7B%0A    
@@ -2454,99 +2454,8 @@
 n%22);
-%0A%0A                tryExpressions.add((CallExpression) getOnlyElement(call.getArguments()));
 %0A   
@@ -2593,32 +2593,162 @@
 %0A            %7D%0A%0A
+            if (isTry) %7B%0A                tryExpressions.add((CallExpression) getOnlyElement(call.getArguments()));%0A            %7D%0A%0A
             retu
@@ -2964,18 +2964,19 @@
 essionsP
-re
+ost
 Order()%0A
@@ -3030,18 +3030,8 @@
 ld()
-.reverse()
 ;%0A  

Simplify code and fix naming in TryExpressionExtractor