package com.lanyuanxiaoyao.service.sync.configuration;

import com.lanyuanxiaoyao.service.common.Constants;
import java.util.HashMap;
import java.util.Map;
import org.apache.hudi.common.model.OverwriteWithLatestAvroPayload;
import org.apache.hudi.common.util.Option;
import org.apache.hudi.org.apache.avro.generic.GenericRecord;
import org.apache.hudi.org.apache.avro.util.Utf8;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lanyuanxiaoyao
 * @date 2023-04-18
 */
public class TraceOverwriteWithLatestAvroPayload extends OverwriteWithLatestAvroPayload {
    private static final Logger logger = LoggerFactory.getLogger(TraceOverwriteWithLatestAvroPayload.class);

    private final String latestOpts;

    public TraceOverwriteWithLatestAvroPayload(GenericRecord record, Comparable orderingVal) {
        super(record, orderingVal);
        this.latestOpts = updateLatestOpts(Option.ofNullable(record));
    }

    public TraceOverwriteWithLatestAvroPayload(Option<GenericRecord> record) {
        super(record);
        this.latestOpts = updateLatestOpts(record);
    }

    private String updateLatestOpts(Option<GenericRecord> record) {
        try {
            return record
                    .map(r -> ((Utf8) r.get(Constants.LATEST_OPERATION_TIMESTAMP_KEY_NAME)).toString())
                    .orElse(null);
        } catch (Throwable throwable) {
            logger.error("Get latest opts failure", throwable);
        }
        return null;
    }

    @Override
    public Option<Map<String, String>> getMetadata() {
        if (this.latestOpts == null) {
            return Option.empty();
        }
        Map<String, String> metadata = super.getMetadata().orElse(new HashMap<>());
        metadata.put(Constants.LATEST_OPERATION_TIMESTAMP_KEY_NAME, this.latestOpts);
        return Option.of(metadata);
    }
}
