package org.apache.hudi.common.model;

import com.lanyuanxiaoyao.service.common.Constants;
import java.util.HashMap;
import java.util.Map;
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.apache.hudi.table.HoodieTableFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 通过将latest_op_ts值写入payload进行传递，使压缩完成后可以从status中获取该值
 * Hudi默认使用{@link OverwriteWithLatestAvroPayload}，由于{@link HoodieTableFactory}156行中的说明
 * 如果使用默认值，则改为使用{@link EventTimeAvroPayload}，所以这里的payload直接继承EventTimeAvroPayload
 * 从而符合原来的使用逻辑
 *
 * @author lanyuanxiaoyao
 * @date 2023-04-18
 */
public class TraceEventTimeAvroPayload extends EventTimeAvroPayload {
    private static final Logger logger = LoggerFactory.getLogger(TraceEventTimeAvroPayload.class);

    private final Map<String, String> metadata = new HashMap<>();

    public TraceEventTimeAvroPayload(GenericRecord record, Comparable orderingVal) {
        super(record, orderingVal);
        updateLatestOpts(Option.ofNullable(record));
    }

    public TraceEventTimeAvroPayload(Option<GenericRecord> record) {
        super(record);
        updateLatestOpts(record);
    }

    private void updateLatestOpts(Option<GenericRecord> record) {
        try {
            record
                    .map(r -> ((Utf8) r.get(Constants.LATEST_OPERATION_TIMESTAMP_KEY_NAME)).toString())
                    .ifPresent(latestOpts -> metadata.put(Constants.LATEST_OPERATION_TIMESTAMP_KEY_NAME, latestOpts));
        } catch (Throwable throwable) {
            logger.error("Get latest opts failure", throwable);
        }
    }

    @Override
    public Option<Map<String, String>> getMetadata() {
        return Option.of(metadata);
    }
}
