/*
 * 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.apache.hadoop.hbase.client.metrics.ServerSideScanMetrics.COUNT_OF_ROWS_SCANNED_KEY_METRIC_NAME;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HBaseTestingUtil;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
import org.apache.hadoop.hbase.client.metrics.ScanMetricsRegionInfo;
import org.apache.hadoop.hbase.filter.FilterBase;
import org.apache.hadoop.hbase.io.hfile.BlockCache;
import org.apache.hadoop.hbase.io.hfile.IndexOnlyLruBlockCache;
import org.apache.hadoop.hbase.regionserver.HStore;
import org.apache.hadoop.hbase.regionserver.HStoreFile;
import org.apache.hadoop.hbase.regionserver.RegionScanner;
import org.apache.hadoop.hbase.regionserver.StoreScanner;
import org.apache.hadoop.hbase.testclassification.ClientTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;

@Tag(SmallTests.TAG)
@Tag(ClientTests.TAG)
public class TestClientSideRegionScanner {
  private final static HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil();
  private static final TableName TABLE_NAME = TableName.valueOf("test");
  private static final byte[] FAM_NAME = Bytes.toBytes("f");

  private Configuration conf;
  private Path rootDir;
  private FileSystem fs;
  private TableDescriptor htd;
  private RegionInfo hri;
  private Scan scan;
  private String methodName;

  @BeforeAll
  public static void setUpBeforeClass() throws Exception {
    TEST_UTIL.startMiniCluster(1);
  }

  @AfterAll
  public static void tearDownAfterClass() throws Exception {
    TEST_UTIL.shutdownMiniCluster();
  }

  @BeforeEach
  public void setup(TestInfo testInfo) throws IOException {
    this.methodName = testInfo.getTestMethod().get().getName();
    conf = TEST_UTIL.getConfiguration();
    rootDir = TEST_UTIL.getDefaultRootDirPath();
    fs = TEST_UTIL.getTestFileSystem();
    htd = TEST_UTIL.getAdmin().getDescriptor(TableName.META_TABLE_NAME);
    hri = TEST_UTIL.getAdmin().getRegions(TableName.META_TABLE_NAME).get(0);
    scan = new Scan();
  }

  @Test
  public void testDefaultBlockCache() throws IOException {
    Configuration copyConf = new Configuration(conf);
    try (ClientSideRegionScanner clientSideRegionScanner =
      new ClientSideRegionScanner(copyConf, fs, rootDir, htd, hri, scan, null)) {
      BlockCache blockCache = clientSideRegionScanner.getRegion().getBlockCache();
      assertNotNull(blockCache);
      assertThat(blockCache, instanceOf(IndexOnlyLruBlockCache.class));
      assertEquals(HConstants.HBASE_CLIENT_SCANNER_ONHEAP_BLOCK_CACHE_FIXED_SIZE_DEFAULT,
        blockCache.getMaxSize());
    }
  }

  @Test
  public void testConfiguredBlockCache() throws IOException {
    Configuration copyConf = new Configuration(conf);
    // tiny 1MB fixed cache size
    long blockCacheFixedSize = 1024 * 1024L;
    copyConf.setLong(HConstants.HFILE_ONHEAP_BLOCK_CACHE_FIXED_SIZE_KEY, blockCacheFixedSize);
    try (ClientSideRegionScanner clientSideRegionScanner =
      new ClientSideRegionScanner(copyConf, fs, rootDir, htd, hri, scan, null)) {
      BlockCache blockCache = clientSideRegionScanner.getRegion().getBlockCache();
      assertNotNull(blockCache);
      assertThat(blockCache, instanceOf(IndexOnlyLruBlockCache.class));
      assertEquals(blockCacheFixedSize, blockCache.getMaxSize());
    }
  }

  @Test
  public void testNoBlockCache() throws IOException {
    Configuration copyConf = new Configuration(conf);
    copyConf.setFloat(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY, 0.0f);
    try (ClientSideRegionScanner clientSideRegionScanner =
      new ClientSideRegionScanner(copyConf, fs, rootDir, htd, hri, scan, null)) {
      BlockCache blockCache = clientSideRegionScanner.getRegion().getBlockCache();
      assertNull(blockCache);
    }
  }

  @Test
  public void testContinuesToScanIfHasMore() throws IOException {
    // Conditions for this test to set up RegionScannerImpl to bail on the scan
    // after a single iteration
    // 1. Configure preadMaxBytes to something small to trigger scannerContext#returnImmediately
    // 2. Configure a filter to filter out some rows, in this case rows with values < 5
    // 3. Configure the filter's hasFilterRow to return true so RegionScannerImpl sets
    // the limitScope to something with a depth of 0, so we bail on the scan after the first
    // iteration

    Configuration copyConf = new Configuration(conf);
    copyConf.setLong(StoreScanner.STORESCANNER_PREAD_MAX_BYTES, 1);
    Scan scan = new Scan();
    scan.setFilter(new FiltersRowsLessThan5());
    scan.setLimit(1);

    try (Table table = TEST_UTIL.createTable(TABLE_NAME, FAM_NAME)) {
      TableDescriptor htd = TEST_UTIL.getAdmin().getDescriptor(TABLE_NAME);
      RegionInfo hri = TEST_UTIL.getAdmin().getRegions(TABLE_NAME).get(0);

      for (int i = 0; i < 10; ++i) {
        table.put(createPut(i));
      }

      // Flush contents to disk so we can scan the fs
      TEST_UTIL.getAdmin().flush(TABLE_NAME);

      try (ClientSideRegionScanner clientSideRegionScanner =
        new ClientSideRegionScanner(copyConf, fs, rootDir, htd, hri, scan, null)) {
        RegionScanner scannerSpy = spy(clientSideRegionScanner.scanner);
        clientSideRegionScanner.scanner = scannerSpy;
        Result result = clientSideRegionScanner.next();

        verify(scannerSpy, times(6)).nextRaw(anyList());
        assertNotNull(result);
        assertEquals(Bytes.toInt(result.getRow()), 5);
        assertTrue(clientSideRegionScanner.hasMore);

        for (int i = 6; i < 10; ++i) {
          result = clientSideRegionScanner.next();
          verify(scannerSpy, times(i + 1)).nextRaw(anyList());
          assertNotNull(result);
          assertEquals(Bytes.toInt(result.getRow()), i);
        }

        result = clientSideRegionScanner.next();
        assertNull(result);
        assertFalse(clientSideRegionScanner.hasMore);
      }
    }
  }

  @Test
  public void testScanMetricsDisabled() throws IOException {
    Configuration copyConf = new Configuration(conf);
    Scan scan = new Scan();
    try (ClientSideRegionScanner clientSideRegionScanner =
      new ClientSideRegionScanner(copyConf, fs, rootDir, htd, hri, scan, null)) {
      clientSideRegionScanner.next();
      assertNull(clientSideRegionScanner.getScanMetrics());
    }
  }

  private void testScanMetricsWithScanMetricsByRegionDisabled(ScanMetrics scanMetrics)
    throws IOException {
    Configuration copyConf = new Configuration(conf);
    Scan scan = new Scan();
    scan.setScanMetricsEnabled(true);
    TEST_UTIL.getAdmin().flush(TableName.META_TABLE_NAME);
    try (ClientSideRegionScanner clientSideRegionScanner =
      new ClientSideRegionScanner(copyConf, fs, rootDir, htd, hri, scan, scanMetrics)) {
      clientSideRegionScanner.next();
      ScanMetrics scanMetricsFromScanner = clientSideRegionScanner.getScanMetrics();
      assertNotNull(scanMetricsFromScanner);
      if (scanMetrics != null) {
        assertSame(scanMetrics, scanMetricsFromScanner);
      }
      Map<String, Long> metricsMap = scanMetricsFromScanner.getMetricsMap(false);
      assertTrue(metricsMap.get(COUNT_OF_ROWS_SCANNED_KEY_METRIC_NAME) > 0);
      assertTrue(scanMetricsFromScanner.collectMetricsByRegion(false).isEmpty());
    }
  }

  @Test
  public void testScanMetricsNotAsInputWithScanMetricsByRegionDisabled() throws IOException {
    testScanMetricsWithScanMetricsByRegionDisabled(null);
  }

  @Test
  public void testScanMetricsAsInputWithScanMetricsByRegionDisabled() throws IOException {
    testScanMetricsWithScanMetricsByRegionDisabled(new ScanMetrics());
  }

  private void testScanMetricByRegion(ScanMetrics scanMetrics) throws IOException {
    Configuration copyConf = new Configuration(conf);
    Scan scan = new Scan();
    scan.setEnableScanMetricsByRegion(true);
    TEST_UTIL.getAdmin().flush(TableName.META_TABLE_NAME);
    try (ClientSideRegionScanner clientSideRegionScanner =
      new ClientSideRegionScanner(copyConf, fs, rootDir, htd, hri, scan, scanMetrics)) {
      clientSideRegionScanner.next();
      ScanMetrics scanMetricsFromScanner = clientSideRegionScanner.getScanMetrics();
      assertNotNull(scanMetricsFromScanner);
      if (scanMetrics != null) {
        assertSame(scanMetrics, scanMetricsFromScanner);
      }
      Map<ScanMetricsRegionInfo, Map<String, Long>> scanMetricsByRegion =
        scanMetricsFromScanner.collectMetricsByRegion();
      assertEquals(1, scanMetricsByRegion.size());
      for (Map.Entry<ScanMetricsRegionInfo, Map<String, Long>> entry : scanMetricsByRegion
        .entrySet()) {
        ScanMetricsRegionInfo scanMetricsRegionInfo = entry.getKey();
        Map<String, Long> metricsMap = entry.getValue();
        assertEquals(hri.getEncodedName(), scanMetricsRegionInfo.getEncodedRegionName());
        assertNull(scanMetricsRegionInfo.getServerName());
        assertTrue(metricsMap.get(COUNT_OF_ROWS_SCANNED_KEY_METRIC_NAME) > 0);
        assertEquals((long) metricsMap.get(COUNT_OF_ROWS_SCANNED_KEY_METRIC_NAME),
          scanMetricsFromScanner.countOfRowsScanned.get());
      }
    }
  }

  @Test
  public void testScanMetricsByRegionWithoutScanMetricsAsInput() throws IOException {
    testScanMetricByRegion(null);
  }

  @Test
  public void testScanMetricsByRegionWithScanMetricsAsInput() throws IOException {
    testScanMetricByRegion(new ScanMetrics());
  }

  @Test
  public void testGetFilesRead() throws Exception {
    // Create a table and add some data
    TableName tableName = TableName.valueOf(methodName);
    try (Table table = TEST_UTIL.createTable(tableName, new byte[][] { FAM_NAME })) {
      TableDescriptor tableHtd = TEST_UTIL.getAdmin().getDescriptor(tableName);
      RegionInfo tableHri = TEST_UTIL.getAdmin().getRegions(tableName).get(0);

      // Add some data
      for (int i = 0; i < 5; i++) {
        byte[] row = Bytes.toBytes(i);
        Put put = new Put(row);
        put.addColumn(FAM_NAME, row, row);
        table.put(put);
      }

      // Flush contents to disk so we can scan the fs
      TEST_UTIL.getAdmin().flush(tableName);

      // Create ClientSideRegionScanner with the correct table descriptor and region info
      Configuration copyConf = new Configuration(conf);
      Scan tableScan = new Scan();
      ClientSideRegionScanner clientSideRegionScanner =
        new ClientSideRegionScanner(copyConf, fs, rootDir, tableHtd, tableHri, tableScan, null);

      // Get expected file paths from the region before closing
      // (after closing, the region will be closed too)
      Set<Path> expectedFilePaths = new HashSet<>();
      HStore store = clientSideRegionScanner.getRegion().getStore(FAM_NAME);
      for (HStoreFile storeFile : store.getStorefiles()) {
        Path qualifiedPath = fs.makeQualified(storeFile.getPath());
        expectedFilePaths.add(qualifiedPath);
      }
      int expectedFileCount = expectedFilePaths.size();
      assertTrue(expectedFileCount >= 1, "Should have at least one store file after flush");

      // Before closing, should return empty set
      Set<Path> filesReadBeforeClose = clientSideRegionScanner.getFilesRead();
      assertTrue(filesReadBeforeClose.isEmpty(), "Should return empty set before closing");

      // Scan through some results
      Result result;
      int count = 0;
      while ((result = clientSideRegionScanner.next()) != null && count < 3) {
        assertNotNull(result, "Result should not be null");
        count++;
      }

      // Still should return empty set before closing
      filesReadBeforeClose = clientSideRegionScanner.getFilesRead();
      assertTrue(filesReadBeforeClose.isEmpty(),
        "Should return empty set before closing even after scanning");

      // Close the scanner - this should collect files from the underlying scanner
      clientSideRegionScanner.close();

      // After closing, should return files from the underlying scanner
      Set<Path> filesReadAfterClose = clientSideRegionScanner.getFilesRead();
      // Verify exact file count
      assertEquals(expectedFileCount, filesReadAfterClose.size(),
        "Should have exact file count after closing");
      // Verify exact file names match
      assertEquals(expectedFilePaths, filesReadAfterClose,
        "Should contain all expected file paths");
    } finally {
      TEST_UTIL.deleteTable(tableName);
    }
  }

  private static Put createPut(int rowAsInt) {
    byte[] row = Bytes.toBytes(rowAsInt);
    Put put = new Put(row);
    put.addColumn(FAM_NAME, row, row);
    return put;
  }

  private static class FiltersRowsLessThan5 extends FilterBase {

    @Override
    public boolean filterRowKey(Cell cell) {
      byte[] rowKey = Arrays.copyOfRange(cell.getRowArray(), cell.getRowOffset(),
        cell.getRowLength() + cell.getRowOffset());
      int intValue = Bytes.toInt(rowKey);
      return intValue < 5;
    }

    @Override
    public boolean hasFilterRow() {
      return true;
    }
  }
}
