package com.lanyuanxiaoyao.service.sync.configuration;

import cn.hutool.core.util.StrUtil;
import com.lanyuanxiaoyao.service.common.Constants;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import org.apache.hudi.client.WriteStatus;
import org.apache.hudi.common.model.HoodieRecord;
import org.apache.hudi.common.util.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lanyuanxiaoyao
 * @date 2023-04-17
 */
public class TraceWriteStatus extends WriteStatus {
    private static final Logger logger = LoggerFactory.getLogger(TraceWriteStatus.class);
    private final static DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private long latestOpts = 0L;

    public TraceWriteStatus() {
        super();
    }

    public TraceWriteStatus(Boolean trackSuccessRecords, Double failureFraction) {
        super(trackSuccessRecords, failureFraction);
    }

    public long getLatestOpts() {
        return latestOpts;
    }

    @Override
    public void markSuccess(HoodieRecord record, Option<Map<String, String>> optionalRecordMetadata) {
        super.markSuccess(record, optionalRecordMetadata);
        try {
            optionalRecordMetadata.ifPresent(map -> {
                if (map.containsKey(Constants.LATEST_OPERATION_TIMESTAMP_KEY_NAME)) {
                    String inOpts = map.get(Constants.LATEST_OPERATION_TIMESTAMP_KEY_NAME);
                    if (StrUtil.isNotBlank(inOpts)) {
                        long current = LocalDateTime.parse(inOpts, FORMATTER).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
                        latestOpts = Long.max(latestOpts, current);
                    }
                }
            });
        } catch (Throwable throwable) {
            logger.error("Parse latest opts failure", throwable);
        }
    }

    @Override
    public void markFailure(HoodieRecord record, Throwable t, Option<Map<String, String>> optionalRecordMetadata) {
        super.markFailure(record, t, optionalRecordMetadata);
    }
}
