/*
 * Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
 * 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 io.prestosql.plugin.hive;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import io.airlift.testing.mysql.TestingMySqlServer;
import io.airlift.tpch.TpchTable;
import io.prestosql.tests.AbstractTestStarTreeQueries;
import io.prestosql.tests.DistributedQueryRunner;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;

import java.util.Optional;
import java.util.Random;

import static io.airlift.tpch.TpchTable.getTables;

@Test
public class TestHiveDistributedStarTreeQueries
        extends AbstractTestStarTreeQueries
{
    private final TestingMySqlServer mysqlServer;

    public TestHiveDistributedStarTreeQueries()
            throws Exception
    {
        this(createTestingMySqlServer());
    }

    public TestHiveDistributedStarTreeQueries(TestingMySqlServer mysqlServer)
    {
        super(() -> createQueryRunnerWithMetaStore(getTables(), mysqlServer));
        this.mysqlServer = mysqlServer;
    }

    private static TestingMySqlServer createTestingMySqlServer()
            throws Exception
    {
        return new TestingMySqlServer("user", "testpass", "cube_meta_store_" + new Random().nextInt(10000000));
    }

    public static DistributedQueryRunner createQueryRunnerWithMetaStore(Iterable<TpchTable<?>> tables, TestingMySqlServer mySqlServer)
            throws Exception
    {
        return HiveQueryRunner.createQueryRunner(tables, ImmutableMap.of(), "sql-standard", ImmutableMap.of(), Optional.empty(), false, mySqlServer.getJdbcUrl(Iterables.getOnlyElement(mySqlServer.getDatabases())));
    }

    @AfterClass(alwaysRun = true)
    public final void destroy()
    {
        mysqlServer.close();
    }
}
