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

import static org.apache.parquet.column.ParquetProperties.WriterVersion.PARQUET_1_0;
import static org.apache.parquet.column.ParquetProperties.WriterVersion.PARQUET_2_0;
import static org.apache.parquet.hadoop.ParquetFileWriter.Mode.OVERWRITE;
import static org.apache.parquet.hadoop.TestBloomFiltering.generateDictionaryData;
import static org.assertj.core.api.Assertions.assertThat;

import java.io.IOException;
import java.nio.file.Files;
import java.util.Collections;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.parquet.ParquetReadOptions;
import org.apache.parquet.bytes.HeapByteBufferAllocator;
import org.apache.parquet.bytes.TrackingByteBufferAllocator;
import org.apache.parquet.column.EncodingStats;
import org.apache.parquet.column.ParquetProperties.WriterVersion;
import org.apache.parquet.filter2.recordlevel.PhoneBookWriter;
import org.apache.parquet.hadoop.example.ExampleParquetWriter;
import org.apache.parquet.hadoop.metadata.BlockMetaData;
import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData;
import org.apache.parquet.hadoop.util.HadoopInputFile;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;

public class TestStoreBloomFilter {
  private static final Path FILE_V1 = createTempFile(PARQUET_1_0);
  private static final Path FILE_V2 = createTempFile(PARQUET_2_0);
  private static final List<PhoneBookWriter.User> DATA = Collections.unmodifiableList(generateDictionaryData(10000));

  @BeforeAll
  public static void createFiles() throws IOException {
    writePhoneBookToFile(FILE_V1, PARQUET_1_0);
    writePhoneBookToFile(FILE_V2, PARQUET_2_0);
  }

  @AfterAll
  public static void deleteFiles() throws IOException {
    deleteFile(FILE_V1);
    deleteFile(FILE_V2);
  }

  @ParameterizedTest(name = "WriterVersion = {0}")
  @EnumSource(WriterVersion.class)
  public void testStoreBloomFilter(WriterVersion writerVersion) throws IOException {
    Path file = fileForWriterVersion(writerVersion);
    try (TrackingByteBufferAllocator allocator = TrackingByteBufferAllocator.wrap(new HeapByteBufferAllocator());
        ParquetFileReader reader = new ParquetFileReader(
            HadoopInputFile.fromPath(file, new Configuration()),
            ParquetReadOptions.builder().withAllocator(allocator).build())) {
      List<BlockMetaData> blocks = reader.getRowGroups();
      blocks.forEach(block -> {
        try {
          // column `id` isn't fully encoded in dictionary, it will generate `BloomFilter`
          ColumnChunkMetaData idMeta = block.getColumns().get(0);
          EncodingStats idEncoding = idMeta.getEncodingStats();
          assertThat(idEncoding.hasNonDictionaryEncodedPages()).isTrue();
          assertThat(reader.readBloomFilter(idMeta)).isNotNull();

          // column `name` is fully encoded in dictionary, it won't generate `BloomFilter`
          ColumnChunkMetaData nameMeta = block.getColumns().get(1);
          EncodingStats nameEncoding = nameMeta.getEncodingStats();
          assertThat(nameEncoding.hasNonDictionaryEncodedPages()).isFalse();
          assertThat(reader.readBloomFilter(nameMeta)).isNull();
        } catch (IOException e) {
          e.printStackTrace();
        }
      });
    }
  }

  private static Path fileForWriterVersion(WriterVersion writerVersion) {
    switch (writerVersion) {
      case PARQUET_1_0:
        return FILE_V1;
      case PARQUET_2_0:
        return FILE_V2;
      default:
        throw new IllegalArgumentException("Unexpected writer version: " + writerVersion);
    }
  }

  private static Path createTempFile(WriterVersion writerVersion) {
    try {
      return new Path(Files.createTempFile("test-store-bloom-filter-" + writerVersion, ".parquet")
          .toAbsolutePath()
          .toString());
    } catch (IOException e) {
      throw new AssertionError("Unable to create temporary file", e);
    }
  }

  private static void deleteFile(Path file) throws IOException {
    file.getFileSystem(new Configuration()).delete(file, false);
  }

  private static void writePhoneBookToFile(Path file, WriterVersion parquetVersion) throws IOException {
    int pageSize = DATA.size() / 100; // Ensure that several pages will be created
    int rowGroupSize = pageSize * 4; // Ensure that there are more row-groups created
    try (TrackingByteBufferAllocator allocator = TrackingByteBufferAllocator.wrap(new HeapByteBufferAllocator())) {
      PhoneBookWriter.write(
          ExampleParquetWriter.builder(file)
              .withAllocator(allocator)
              .withWriteMode(OVERWRITE)
              .withRowGroupSize(rowGroupSize)
              .withPageSize(pageSize)
              .withBloomFilterNDV("id", 10000L)
              .withBloomFilterNDV("name", 10000L)
              .withWriterVersion(parquetVersion),
          DATA);
    }
  }
}
