package com.lanyuanxiaoyao.service.sync.functions.type;

import com.lanyuanxiaoyao.service.common.Constants;
import com.lanyuanxiaoyao.service.common.entity.TableMeta;
import java.util.List;
import java.util.Map;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.StringData;
import org.apache.hudi.org.apache.avro.Schema;
import org.apache.hudi.org.apache.avro.SchemaBuilder;

/**
 * 第一版本的类型转换
 * 所有字段类型都是 String
 *
 * @author ZhangJiacheng
 * @date 2023-07-20
 */
public class TypeConverterV1 implements TypeConverter {
    @Override
    public Schema convertToSchema(TableMeta meta) {
        SchemaBuilder.FieldAssembler<Schema> fieldBuilder = SchemaBuilder.builder()
                .record(meta.getTable())
                .fields();
        fieldBuilder.nullableBoolean(Constants.HUDI_DELETE_KEY_NAME, false);
        fieldBuilder.nullableString(Constants.UNION_KEY_NAME, "");

        meta.getFields().forEach(fieldMeta -> fieldBuilder.optionalString(fieldMeta.getName()));

        fieldBuilder.nullableLong(Constants.UPDATE_TIMESTAMP_KEY_NAME, -1);
        fieldBuilder.nullableString(Constants.LATEST_OPERATION_TIMESTAMP_KEY_NAME, "");
        return fieldBuilder.endRecord();
    }

    @Override
    public GenericRowData convertToGenericRowData(TableMeta meta, Schema schema, Map<String, Object> data) {
        List<Schema.Field> fields = schema.getFields();
        GenericRowData row = new GenericRowData(fields.size());
        for (int index = 0; index < fields.size(); index++) {
            Schema.Field field = fields.get(index);
            // 如果是telepg的话，字段名就要统一改成小写，上游不规范，下游擦屁股
            Object value = data.getOrDefault(Constants.FIELD_COVERT.apply(meta, field.name()), null);
            if (field.schema().getType().equals(Schema.Type.STRING)
                || (field.schema().isUnion() && field.schema().getTypes().contains(Schema.create(Schema.Type.STRING)))
                || value instanceof String) {
                row.setField(index, StringData.fromString((String) value));
            } else {
                row.setField(index, value);
            }
        }
        return row;
    }
}
