/*
 * 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.fluss.row.encode.paimon;

import org.apache.fluss.row.TimestampLtz;
import org.apache.fluss.row.TimestampNtz;
import org.apache.fluss.row.indexed.IndexedRow;
import org.apache.fluss.row.indexed.IndexedRowWriter;
import org.apache.fluss.types.DataField;
import org.apache.fluss.types.DataType;
import org.apache.fluss.types.DataTypes;
import org.apache.fluss.types.RowType;
import org.apache.fluss.utils.TypeUtils;

import org.apache.paimon.data.BinaryRow;
import org.apache.paimon.data.BinaryRowWriter;
import org.apache.paimon.data.BinaryString;
import org.apache.paimon.data.Decimal;
import org.apache.paimon.data.Timestamp;
import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

/** UT for {@link PaimonKeyEncoder} to verify the encoding result is same to Paimon's. */
class PaimonKeyEncoderTest {

    @Test
    void testEncodeKey() {
        // create a row with all types
        RowType keyRowType = createKeyRowType();
        DataType[] allDataTypes = keyRowType.getChildren().toArray(new DataType[0]);
        IndexedRow indexedRow = genFlussRowForAllTypes(allDataTypes);
        List<String> encodedKeys = keyRowType.getFieldNames();
        PaimonKeyEncoder paimonKeyEncoder = new PaimonKeyEncoder(keyRowType, encodedKeys);

        // encode with Fluss own implementation for Paimon
        byte[] encodedKey = paimonKeyEncoder.encodeKey(indexedRow);

        // encode with Paimon implementation
        byte[] paimonEncodedKey = genPaimonRowForAllTypes(keyRowType.getFieldCount()).toBytes();

        // verify both the result should be same
        assertThat(encodedKey).isEqualTo(paimonEncodedKey);
    }

    private IndexedRow genFlussRowForAllTypes(DataType[] dataTypes) {
        IndexedRow indexedRow = new IndexedRow(dataTypes);
        IndexedRowWriter writer = new IndexedRowWriter(dataTypes);
        writer.writeBoolean(true);
        writer.writeByte((byte) 2);
        writer.writeShort(Short.parseShort("10"));
        writer.writeInt(100);
        writer.writeLong(new BigInteger("12345678901234567890").longValue());
        writer.writeFloat(Float.parseFloat("13.2"));
        writer.writeDouble(Double.parseDouble("15.21"));
        writer.writeInt((int) TypeUtils.castFromString("2023-10-25", DataTypes.DATE()));
        writer.writeInt((int) TypeUtils.castFromString("09:30:00.0", DataTypes.TIME()));
        writer.writeBinary("1234567890".getBytes(), 20);
        writer.writeBytes("20".getBytes());
        writer.writeChar(org.apache.fluss.row.BinaryString.fromString("1"), 2);
        writer.writeString(org.apache.fluss.row.BinaryString.fromString("hello"));
        writer.writeDecimal(org.apache.fluss.row.Decimal.fromUnscaledLong(9, 5, 2), 5);
        writer.writeDecimal(
                org.apache.fluss.row.Decimal.fromBigDecimal(new BigDecimal(10), 20, 0), 20);
        writer.writeTimestampNtz(TimestampNtz.fromMillis(1698235273182L), 1);
        writer.writeTimestampNtz(TimestampNtz.fromMillis(1698235273182L), 5);
        writer.writeTimestampLtz(TimestampLtz.fromEpochMillis(1698235273182L, 45678), 1);
        writer.writeTimestampLtz(TimestampLtz.fromEpochMillis(1698235273182L, 123456), 6);
        indexedRow.pointTo(writer.segment(), 0, writer.position());
        return indexedRow;
    }

    private BinaryRow genPaimonRowForAllTypes(int arity) {
        BinaryRow binaryRow = new BinaryRow(arity);
        BinaryRowWriter binaryRowWriter = new BinaryRowWriter(binaryRow);
        binaryRowWriter.writeBoolean(0, true);
        binaryRowWriter.writeByte(1, (byte) 2);
        binaryRowWriter.writeShort(2, Short.parseShort("10"));
        binaryRowWriter.writeInt(3, 100);
        binaryRowWriter.writeLong(4, new BigInteger("12345678901234567890").longValue());
        binaryRowWriter.writeFloat(5, Float.parseFloat("13.2"));
        binaryRowWriter.writeDouble(6, Double.parseDouble("15.21"));
        binaryRowWriter.writeInt(
                7,
                (int)
                        TypeUtils.castFromString(
                                "2023-10-25", org.apache.fluss.types.DataTypes.DATE()));
        binaryRowWriter.writeInt(
                8,
                (int)
                        TypeUtils.castFromString(
                                "09:30:00.0", org.apache.fluss.types.DataTypes.TIME()));
        binaryRowWriter.writeBinary(9, "1234567890".getBytes());
        binaryRowWriter.writeBinary(10, "20".getBytes());
        binaryRowWriter.writeString(11, BinaryString.fromString("1"));
        binaryRowWriter.writeString(12, BinaryString.fromString("hello"));
        binaryRowWriter.writeDecimal(13, Decimal.fromUnscaledLong(9, 5, 2), 5);
        binaryRowWriter.writeDecimal(14, Decimal.fromBigDecimal(new BigDecimal(10), 20, 0), 20);
        binaryRowWriter.writeTimestamp(15, Timestamp.fromEpochMillis(1698235273182L), 1);
        binaryRowWriter.writeTimestamp(16, Timestamp.fromEpochMillis(1698235273182L), 5);
        binaryRowWriter.writeTimestamp(17, Timestamp.fromEpochMillis(1698235273182L, 45678), 1);
        binaryRowWriter.writeTimestamp(18, Timestamp.fromEpochMillis(1698235273182L, 123456), 6);
        binaryRowWriter.complete();
        return binaryRow;
    }

    public static RowType createKeyRowType() {
        return DataTypes.ROW(
                new DataField("a", DataTypes.BOOLEAN()),
                new DataField("b", DataTypes.TINYINT()),
                new DataField("c", DataTypes.SMALLINT()),
                new DataField("d", DataTypes.INT()),
                new DataField("e", DataTypes.BIGINT()),
                new DataField("f", DataTypes.FLOAT()),
                new DataField("g", DataTypes.DOUBLE()),
                new DataField("h", DataTypes.DATE()),
                new DataField("i", DataTypes.TIME()),
                new DataField("j", DataTypes.BINARY(20)),
                new DataField("k", DataTypes.BYTES()),
                new DataField("l", DataTypes.CHAR(2)),
                new DataField("m", DataTypes.STRING()),
                new DataField("n", DataTypes.DECIMAL(5, 2)),
                new DataField("o", DataTypes.DECIMAL(20, 0)),
                new DataField("p", DataTypes.TIMESTAMP(1)),
                new DataField("q", DataTypes.TIMESTAMP(5)),
                new DataField("r", DataTypes.TIMESTAMP_LTZ(1)),
                new DataField("s", DataTypes.TIMESTAMP_LTZ(5)));
    }
}
