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

import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;
import org.apache.iceberg.types.Type;
import org.apache.iceberg.util.UUIDUtil;
import org.apache.parquet.io.api.Binary;
import org.apache.parquet.schema.LogicalTypeAnnotation.DecimalLogicalTypeAnnotation;
import org.apache.parquet.schema.PrimitiveType;

class ParquetConversions {
  private ParquetConversions() {}

  @SuppressWarnings("unchecked")
  static <T> T convertValue(Type type, PrimitiveType parquetType, Object value) {
    switch (type.typeId()) {
      case BOOLEAN:
      case INTEGER:
      case DATE:
      case TIME:
      case TIMESTAMP:
      case TIMESTAMP_NANO:
      case LONG:
      case FLOAT:
      case DOUBLE:
        return (T) value;
      case STRING:
        return (T) ((Binary) value).toStringUsingUTF8();
      case UUID:
        return (T) UUIDUtil.convert(((Binary) value).toByteBuffer());
      case FIXED:
      case BINARY:
        return (T) ((Binary) value).toByteBuffer();
      case DECIMAL:
        int scale =
            ((DecimalLogicalTypeAnnotation) parquetType.getLogicalTypeAnnotation()).getScale();
        switch (parquetType.getPrimitiveTypeName()) {
          case INT32:
          case INT64:
            return (T) BigDecimal.valueOf(((Number) value).longValue(), scale);
          case FIXED_LEN_BYTE_ARRAY:
          case BINARY:
            return (T) new BigDecimal(new BigInteger(((Binary) value).getBytes()), scale);
          default:
            throw new IllegalArgumentException(
                "Unsupported primitive type for decimal: " + parquetType.getPrimitiveTypeName());
        }
      default:
        throw new IllegalArgumentException("Unsupported primitive type: " + type);
    }
  }

  static Function<Object, Object> converterFromParquet(
      PrimitiveType parquetType, Type icebergType) {
    Function<Object, Object> fromParquet = converterFromParquet(parquetType);
    if (icebergType != null) {
      if (icebergType.typeId() == Type.TypeID.LONG
          && parquetType.getPrimitiveTypeName() == PrimitiveType.PrimitiveTypeName.INT32) {
        return value -> ((Integer) fromParquet.apply(value)).longValue();
      } else if (icebergType.typeId() == Type.TypeID.DOUBLE
          && parquetType.getPrimitiveTypeName() == PrimitiveType.PrimitiveTypeName.FLOAT) {
        return value -> ((Float) fromParquet.apply(value)).doubleValue();
      } else if (icebergType.typeId() == Type.TypeID.UUID) {
        return binary -> UUIDUtil.convert(((Binary) binary).toByteBuffer());
      }
    }

    return fromParquet;
  }

  static Function<Object, Object> converterFromParquet(PrimitiveType type) {
    if (type.getOriginalType() != null) {
      switch (type.getOriginalType()) {
        case UTF8:
          // decode to CharSequence to avoid copying into a new String
          return binary -> StandardCharsets.UTF_8.decode(((Binary) binary).toByteBuffer());
        case DECIMAL:
          DecimalLogicalTypeAnnotation decimal =
              (DecimalLogicalTypeAnnotation) type.getLogicalTypeAnnotation();
          int scale = decimal.getScale();
          switch (type.getPrimitiveTypeName()) {
            case INT32:
            case INT64:
              return num -> BigDecimal.valueOf(((Number) num).longValue(), scale);
            case FIXED_LEN_BYTE_ARRAY:
            case BINARY:
              return bin -> new BigDecimal(new BigInteger(((Binary) bin).getBytes()), scale);
            default:
              throw new IllegalArgumentException(
                  "Unsupported primitive type for decimal: " + type.getPrimitiveTypeName());
          }
        default:
      }
    }

    switch (type.getPrimitiveTypeName()) {
      case FIXED_LEN_BYTE_ARRAY:
      case BINARY:
        return binary -> ByteBuffer.wrap(((Binary) binary).getBytes());
      case INT96:
        return binary ->
            ParquetUtil.extractTimestampInt96(
                ByteBuffer.wrap(((Binary) binary).getBytes()).order(ByteOrder.LITTLE_ENDIAN));
      default:
    }

    return obj -> obj;
  }
}
