package com.lanyuanxiaoyao.service.sync.configuration;

import org.apache.hudi.avro.HoodieAvroUtils;
import org.apache.hudi.common.config.TypedProperties;
import org.apache.hudi.common.util.PartitionPathEncodeUtils;
import org.apache.hudi.configuration.FlinkOptions;
import org.apache.hudi.keygen.SimpleAvroKeyGenerator;
import org.apache.hudi.org.apache.avro.generic.GenericRecord;

/**
 * @author ZhangJiacheng
 */
public class DefaultPartitionNameKeyGenerator extends SimpleAvroKeyGenerator {
    private final String defaultPartitionName;

    public DefaultPartitionNameKeyGenerator(TypedProperties props) {
        super(props);
        defaultPartitionName = props.getString(FlinkOptions.PARTITION_DEFAULT_NAME.key(), FlinkOptions.PARTITION_DEFAULT_NAME.defaultValue());
    }

    @Override
    public String getPartitionPath(GenericRecord record) {
        String partitionPathField = getPartitionPathFields().get(0);
        String partitionPath = HoodieAvroUtils.getNestedFieldValAsString(record, partitionPathField, true, consistentLogicalTimestampEnabled);
        if (partitionPath == null || partitionPath.isEmpty()) {
            partitionPath = defaultPartitionName;
        }
        if (encodePartitionPath) {
            partitionPath = PartitionPathEncodeUtils.escapePathName(partitionPath);
        }
        if (hiveStylePartitioning) {
            partitionPath = partitionPathField + "=" + partitionPath;
        }
        return partitionPath;
    }
}
