/*
 * 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.iterative.rule.test;

import com.facebook.presto.Session;
import com.facebook.presto.connector.ConnectorId;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.security.AccessControl;
import com.facebook.presto.spi.Plugin;
import com.facebook.presto.sql.planner.iterative.Rule;
import com.facebook.presto.testing.LocalQueryRunner;
import com.facebook.presto.tpch.TpchConnectorFactory;
import com.facebook.presto.transaction.TransactionManager;
import com.google.common.collect.ImmutableMap;

import java.io.Closeable;
import java.util.List;
import java.util.Map;

import static com.facebook.presto.testing.TestingSession.testSessionBuilder;
import static java.util.Collections.emptyList;

public class RuleTester
        implements Closeable
{
    public static final String CATALOG_ID = "local";
    public static final ConnectorId CONNECTOR_ID = new ConnectorId(CATALOG_ID);

    private final Metadata metadata;
    private final Session session;
    private final LocalQueryRunner queryRunner;
    private final TransactionManager transactionManager;
    private final AccessControl accessControl;

    public RuleTester()
    {
        this(emptyList());
    }

    public RuleTester(List<Plugin> plugins)
    {
        this(plugins, ImmutableMap.of());
    }

    public RuleTester(List<Plugin> plugins, Map<String, String> properties)
    {
        Session.SessionBuilder sessionBuilder = testSessionBuilder()
                .setCatalog(CATALOG_ID)
                .setSchema("tiny")
                .setSystemProperty("task_concurrency", "1"); // these tests don't handle exchanges from local parallel

        for (Map.Entry<String, String> entry : properties.entrySet()) {
            sessionBuilder.setSystemProperty(entry.getKey(), entry.getValue());
        }

        session = sessionBuilder.build();

        queryRunner = new LocalQueryRunner(session);
        queryRunner.createCatalog(session.getCatalog().get(),
                new TpchConnectorFactory(1),
                ImmutableMap.of());
        plugins.stream().forEach(queryRunner::installPlugin);

        this.metadata = queryRunner.getMetadata();
        this.transactionManager = queryRunner.getTransactionManager();
        this.accessControl = queryRunner.getAccessControl();
    }

    public RuleAssert assertThat(Rule rule)
    {
        return new RuleAssert(metadata, queryRunner.getStatsCalculator(), queryRunner.getEstimatedExchangesCostCalculator(), session, rule, transactionManager, accessControl);
    }

    @Override
    public void close()
    {
        queryRunner.close();
    }

    public Metadata getMetadata()
    {
        return metadata;
    }

    public ConnectorId getCurrentConnectorId()
    {
        return queryRunner.inTransaction(transactionSession -> metadata.getCatalogHandle(transactionSession, session.getCatalog().get())).get();
    }
}

@@ -1174,24 +1174,51 @@
 va.util.Map;
+%0Aimport java.util.Optional;
 %0A%0Aimport sta
@@ -1973,25 +1973,225 @@
 String%3E 
-propertie
+sessionProperties)%0A    %7B%0A        this(plugins, sessionProperties, Optional.empty());%0A    %7D%0A%0A    public RuleTester(List%3CPlugin%3E plugins, Map%3CString, String%3E sessionProperties, Optional%3CInteger%3E nodeCountForStat
 s)%0A    %7B
@@ -2502,17 +2502,24 @@
 entry : 
-p
+sessionP
 ropertie
@@ -2689,16 +2689,176 @@
 Runner =
+ nodeCountForStats%0A                .map(nodeCount -%3E LocalQueryRunner.queryRunnerWithFakeNodeCountForStats(session, nodeCount))%0A                .orElseGet(() -%3E
  new Loc
@@ -2879,16 +2879,17 @@
 session)
+)
 ;%0A      

Allow emulating worker count in RuleTester