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

import com.facebook.presto.Session;
import com.facebook.presto.matching.Pattern;
import com.facebook.presto.matching.pattern.TypeOfPattern;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.iterative.Lookup;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.PlanVisitor;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ListMultimap;

import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Multimaps.toMultimap;
import static java.util.Objects.requireNonNull;

public class ComposableStatsCalculator
        implements StatsCalculator
{
    private final ListMultimap<Class<?>, Rule> rulesByRootType;

    public ComposableStatsCalculator(List<Rule> rules)
    {
        this.rulesByRootType = rules.stream()
                .peek(rule -> {
                    checkArgument(rule.getPattern() instanceof TypeOfPattern, "Rule pattern must be TypeOfPattern");
                    Class<?> expectedClass = ((TypeOfPattern<?>) rule.getPattern()).expectedClass();
                    checkArgument(!expectedClass.isInterface() && !Modifier.isAbstract(expectedClass.getModifiers()), "Rule must be registered on a concrete class");
                })
                .collect(toMultimap(
                        rule -> ((TypeOfPattern<?>) rule.getPattern()).expectedClass(),
                        rule -> rule,
                        ArrayListMultimap::create));
    }

    private Stream<Rule> getCandidates(PlanNode node)
    {
        for (Class<?> superclass = node.getClass().getSuperclass(); superclass != null; superclass = superclass.getSuperclass()) {
            // This is important because rule ordering, given in the constructor, is significant.
            // We can't check this fully in the constructor, since abstract class may lack `abstract` modifier.
            checkState(rulesByRootType.get(superclass).isEmpty(), "Cannot maintain rule order because there is rule registered for %s", superclass);
        }
        return rulesByRootType.get(node.getClass()).stream();
    }

    @Override
    public PlanNodeStatsEstimate calculateStats(PlanNode node, StatsProvider sourceStats, Lookup lookup, Session session, Map<Symbol, Type> types)
    {
        Visitor visitor = new Visitor(sourceStats, lookup, session, types);
        return node.accept(visitor, null);
    }

    public interface Rule
    {
        Pattern<? extends PlanNode> getPattern();

        Optional<PlanNodeStatsEstimate> calculate(PlanNode node, StatsProvider sourceStats, Lookup lookup, Session session, Map<Symbol, Type> types);
    }

    private class Visitor
            extends PlanVisitor<PlanNodeStatsEstimate, Void>
    {
        private final StatsProvider sourceStats;
        private final Lookup lookup;
        private final Session session;
        private final Map<Symbol, Type> types;

        public Visitor(StatsProvider sourceStats, Lookup lookup, Session session, Map<Symbol, Type> types)
        {
            this.sourceStats = requireNonNull(sourceStats, "sourceStats is null");
            this.lookup = requireNonNull(lookup, "lookup is null");
            this.session = requireNonNull(session, "session is null");
            this.types = ImmutableMap.copyOf(types);
        }

        @Override
        protected PlanNodeStatsEstimate visitPlan(PlanNode node, Void context)
        {
            Iterator<Rule> ruleIterator = getCandidates(node).iterator();
            while (ruleIterator.hasNext()) {
                Rule rule = ruleIterator.next();
                Optional<PlanNodeStatsEstimate> calculatedStats = rule.calculate(node, sourceStats, lookup, session, types);
                if (calculatedStats.isPresent()) {
                    return calculatedStats.get();
                }
            }
            return PlanNodeStatsEstimate.UNKNOWN_STATS;
        }
    }
}

@@ -945,149 +945,45 @@
 com.
-facebook.presto.sql.planner.plan.PlanVisitor;%0Aimport com.google.common.collect.ArrayListMultimap;%0Aimport com.google.common.collect.ImmutableM
+google.common.collect.ArrayListMultim
 ap;%0A
@@ -1391,56 +1391,8 @@
 map;
-%0Aimport static java.util.Objects.requireNonNull;
 %0A%0Apu
@@ -3103,668 +3103,238 @@
     
-Visitor visitor = new Visitor(sourceStats, lookup, session, types);%0A        return node.accept(visitor, null
+Iterator%3CRule%3E ruleIterator = getCandidates(node).iterator(
 );%0A    
-%7D%0A%0A
     
-public interface Rule%0A    %7B%0A        Pattern%3C? extends PlanNode%3E getPattern();%0A%0A        Optional%3CPlanNodeStatsEstimate%3E calculate(PlanNode node, StatsProvider sourceStats, Lookup lookup, Session session, Map%3CSymbol, Type%3E types);%0A    %7D%0A%0A    private class Visitor%0A            extends PlanVisitor%3CPlanNodeStatsEstimate, Void%3E%0A    %7B%0A        private final StatsProvider sourceStats;%0A        private final Lookup lookup;%0A        private final Session session;%0A        private final Map%3CSymbol, Type%3E types;%0A%0A        public Visitor(StatsProvider
+while (ruleIterator.hasNext()) %7B%0A            Rule rule = ruleIterator.next();%0A            Optional%3CPlanNodeStatsEstimate%3E calculatedStats = rule.calculate(node,
  sou
@@ -3347,64 +3347,32 @@
 ts, 
-Lookup lookup, Session session, Map%3CSymbol, Type%3E
+lookup, session,
  types)
+;
 %0A   
@@ -3380,284 +3380,106 @@
     
-%7B%0A
     
-        this.sourceStats = requireNonNull(sourceStats, %22sourceStats is null%22);%0A            this.lookup = requireNonNull(lookup, %22lookup is null%22);%0A            this.session = requireNonNull(session, %22session is null%22);%0A            this.types = ImmutableMap.copyOf(types);
+if (calculatedStats.isPresent()) %7B%0A                return calculatedStats.get();%0A            %7D
 %0A   
@@ -3485,25 +3485,24 @@
       %7D%0A
-%0A
         
 @Overrid
@@ -3497,193 +3497,99 @@
     
-@Override%0A        protected PlanNodeStatsEstimate visitPlan(PlanNode node, Void context)%0A        %7B%0A            Iterator%3CRule%3E ruleIterator = getCandidates(node).iterator();
+return PlanNodeStatsEstimate.UNKNOWN_STATS;%0A    %7D%0A%0A    public interface Rule
 %0A    
+%7B%0A
         
 whil
@@ -3588,98 +3588,51 @@
     
-while (ruleIterator.hasNext()) %7B%0A                Rule rule = ruleIterator.next();%0A        
+Pattern%3C? extends PlanNode%3E getPattern();%0A%0A
     
@@ -3680,37 +3680,37 @@
 late
-dStats = rule.calculate(node,
+(PlanNode node, StatsProvider
  sou
@@ -3710,32 +3710,39 @@
 der sourceStats,
+ Lookup
  lookup, session
@@ -3738,223 +3738,50 @@
 up, 
-s
+S
 ession
-, types);%0A                if (calculatedStats.isPresent()) %7B%0A                    return calculatedStats.get();%0A                %7D%0A            %7D%0A            return PlanNodeStatsEstimate.UNKNOWN_STATS;%0A        %7D
+ session, Map%3CSymbol, Type%3E types);
 %0A   

Remove unnecessary use of Visitor