/*
 * 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.flink.lake;

import org.apache.fluss.flink.lake.split.LakeSnapshotAndFlussLogSplit;
import org.apache.fluss.flink.lake.split.LakeSnapshotSplit;
import org.apache.fluss.flink.source.split.LogSplit;
import org.apache.fluss.flink.source.split.SourceSplitBase;
import org.apache.fluss.lake.serializer.SimpleVersionedSerializer;
import org.apache.fluss.lake.source.LakeSplit;
import org.apache.fluss.metadata.TableBucket;

import org.apache.flink.core.memory.DataInputDeserializer;
import org.apache.flink.core.memory.DataOutputSerializer;

import javax.annotation.Nullable;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static org.apache.fluss.flink.lake.split.LakeSnapshotAndFlussLogSplit.LAKE_SNAPSHOT_FLUSS_LOG_SPLIT_KIND;
import static org.apache.fluss.flink.lake.split.LakeSnapshotSplit.LAKE_SNAPSHOT_SPLIT_KIND;

/** A serializer for lake split. */
public class LakeSplitSerializer {

    private final SimpleVersionedSerializer<LakeSplit> sourceSplitSerializer;

    public LakeSplitSerializer(SimpleVersionedSerializer<LakeSplit> sourceSplitSerializer) {
        this.sourceSplitSerializer = sourceSplitSerializer;
    }

    public void serialize(DataOutputSerializer out, SourceSplitBase split) throws IOException {
        out.writeInt(sourceSplitSerializer.getVersion());
        if (split instanceof LakeSnapshotSplit) {
            LakeSnapshotSplit lakeSplit = (LakeSnapshotSplit) split;
            out.writeInt(lakeSplit.getSplitIndex());
            byte[] serializeBytes = sourceSplitSerializer.serialize(lakeSplit.getLakeSplit());
            out.writeInt(serializeBytes.length);
            out.write(serializeBytes);
        } else if (split instanceof LakeSnapshotAndFlussLogSplit) {
            // writing file store source split
            LakeSnapshotAndFlussLogSplit lakeSnapshotAndFlussLogSplit =
                    ((LakeSnapshotAndFlussLogSplit) split);
            List<LakeSplit> lakeSplits = lakeSnapshotAndFlussLogSplit.getLakeSplits();
            if (lakeSplits == null) {
                // no snapshot data for the bucket
                out.writeBoolean(false);
            } else {
                out.writeBoolean(true);
                out.writeInt(lakeSplits.size());
                for (LakeSplit lakeSplit : lakeSplits) {
                    byte[] serializeBytes = sourceSplitSerializer.serialize(lakeSplit);
                    out.writeInt(serializeBytes.length);
                    out.write(serializeBytes);
                }
            }
            // writing starting/stopping offset
            out.writeLong(lakeSnapshotAndFlussLogSplit.getStartingOffset());
            out.writeLong(
                    lakeSnapshotAndFlussLogSplit
                            .getStoppingOffset()
                            .orElse(LogSplit.NO_STOPPING_OFFSET));
            out.writeLong(lakeSnapshotAndFlussLogSplit.getRecordsToSkip());
            out.writeInt(lakeSnapshotAndFlussLogSplit.getCurrentLakeSplitIndex());
            out.writeBoolean(lakeSnapshotAndFlussLogSplit.isLakeSplitFinished());
        } else {
            throw new UnsupportedOperationException(
                    "Unsupported split type: " + split.getClass().getName());
        }
    }

    public SourceSplitBase deserialize(
            byte splitKind,
            TableBucket tableBucket,
            @Nullable String partition,
            DataInputDeserializer input)
            throws IOException {
        int version = input.readInt();
        if (splitKind == LAKE_SNAPSHOT_SPLIT_KIND) {
            int splitIndex = input.readInt();
            byte[] serializeBytes = new byte[input.readInt()];
            input.read(serializeBytes);
            LakeSplit lakeSplit = sourceSplitSerializer.deserialize(version, serializeBytes);
            return new LakeSnapshotSplit(tableBucket, partition, lakeSplit, splitIndex);
        } else if (splitKind == LAKE_SNAPSHOT_FLUSS_LOG_SPLIT_KIND) {
            List<LakeSplit> lakeSplits = null;
            if (input.readBoolean()) {
                int lakeSplitSize = input.readInt();
                lakeSplits = new ArrayList<>(lakeSplitSize);
                for (int i = 0; i < lakeSplitSize; i++) {
                    byte[] serializeBytes = new byte[input.readInt()];
                    input.read(serializeBytes);
                    lakeSplits.add(sourceSplitSerializer.deserialize(version, serializeBytes));
                }
            }
            long startingOffset = input.readLong();
            long stoppingOffset = input.readLong();
            long recordsToSkip = input.readLong();
            int splitIndex = input.readInt();
            boolean isLakeSplitFinished = input.readBoolean();
            return new LakeSnapshotAndFlussLogSplit(
                    tableBucket,
                    partition,
                    lakeSplits,
                    startingOffset,
                    stoppingOffset,
                    recordsToSkip,
                    splitIndex,
                    isLakeSplitFinished);
        } else {
            throw new UnsupportedOperationException("Unsupported split kind: " + splitKind);
        }
    }
}
