/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.hadoop.hbase.client;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.fail;

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.stream.IntStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseTestingUtil;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.RegionLocations;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.testclassification.ClientTests;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
import org.apache.hadoop.hbase.zookeeper.ReadOnlyZKClient;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hbase.thirdparty.com.google.common.io.Closeables;

@Tag(MediumTests.TAG)
@Tag(ClientTests.TAG)
public class TestZKConnectionRegistry {

  static final Logger LOG = LoggerFactory.getLogger(TestZKConnectionRegistry.class);
  static final HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil();

  private static ZKConnectionRegistry REGISTRY;

  @BeforeAll
  public static void setUp() throws Exception {
    TEST_UTIL.startMiniCluster(3);
    HBaseTestingUtil.setReplicas(TEST_UTIL.getAdmin(), TableName.META_TABLE_NAME, 3);
    REGISTRY = new ZKConnectionRegistry(TEST_UTIL.getConfiguration(), null);
  }

  @AfterAll
  public static void tearDown() throws Exception {
    Closeables.close(REGISTRY, true);
    TEST_UTIL.shutdownMiniCluster();
  }

  @Test
  public void test() throws InterruptedException, ExecutionException, IOException {
    LOG.info("STARTED TEST");
    String clusterId = REGISTRY.getClusterId().get();
    String expectedClusterId = TEST_UTIL.getHBaseCluster().getMaster().getClusterId();
    assertEquals(expectedClusterId, clusterId,
      "Expected " + expectedClusterId + ", found=" + clusterId);
    assertEquals(TEST_UTIL.getHBaseCluster().getMaster().getServerName(),
      REGISTRY.getActiveMaster().get());
    RegionReplicaTestHelper.waitUntilAllMetaReplicasAreReady(TEST_UTIL, REGISTRY);
    RegionLocations locs = REGISTRY.getMetaRegionLocations().get();
    assertEquals(3, locs.getRegionLocations().length);
    IntStream.range(0, 3).forEach(i -> {
      HRegionLocation loc = locs.getRegionLocation(i);
      assertNotNull(loc, "Replica " + i + " doesn't have location");
      assertEquals(TableName.META_TABLE_NAME, loc.getRegion().getTable());
      assertEquals(i, loc.getRegion().getReplicaId());
    });
  }

  @Test
  public void testIndependentZKConnections() throws IOException {
    try (ReadOnlyZKClient zk1 = REGISTRY.getZKClient()) {
      Configuration otherConf = new Configuration(TEST_UTIL.getConfiguration());
      otherConf.set(HConstants.ZOOKEEPER_QUORUM, MiniZooKeeperCluster.HOST);
      try (ZKConnectionRegistry otherRegistry = new ZKConnectionRegistry(otherConf, null)) {
        ReadOnlyZKClient zk2 = otherRegistry.getZKClient();
        assertNotSame(zk1, zk2,
          "Using a different configuration / quorum should result in different "
            + "backing zk connection.");
        assertNotEquals(zk1.getConnectString(), zk2.getConnectString(),
          "Using a different configrution / quorum should be reflected in the zk connection.");
      }
    } finally {
      LOG.info("DONE!");
    }
  }

  @Test
  public void testNoMetaAvailable() throws InterruptedException {
    Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
    conf.set("zookeeper.znode.metaserver", "whatever");
    try (ZKConnectionRegistry registry = new ZKConnectionRegistry(conf, null)) {
      try {
        registry.getMetaRegionLocations().get();
        fail("Should have failed since we set an incorrect meta znode prefix");
      } catch (ExecutionException e) {
        assertThat(e.getCause(), instanceOf(IOException.class));
      }
    }
  }
}
