package com.lanyuanxiaoyao.service.hudi.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lanyuanxiaoyao.service.common.entity.TableMeta;
import com.lanyuanxiaoyao.service.forest.service.InfoService;
import com.lanyuanxiaoyao.service.hudi.utils.HoodieUtils;
import org.apache.hudi.org.apache.avro.Schema;
import org.eclipse.collections.api.map.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

/**
 * Hudi 表服务
 *
 * @author lanyuanxiaoyao
 * @date 2023-07-07
 */
@Service
public class TableService {
    private static final Logger logger = LoggerFactory.getLogger(TableService.class);

    private final ObjectMapper mapper;
    private final InfoService infoService;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    public TableService(Jackson2ObjectMapperBuilder builder, InfoService infoService) {
        this.mapper = builder.build();
        this.infoService = infoService;
    }

    @Cacheable(value = "table-schema", sync = true)
    @Retryable(Throwable.class)
    public ImmutableMap<String, Object> schema(Long flinkJobId, String alias) throws Exception {
        TableMeta meta = infoService.tableMetaDetail(flinkJobId, alias);
        return schema(meta.getHudi().getTargetHdfsPath());
    }

    @Cacheable(value = "table-schema", sync = true)
    @Retryable(Throwable.class)
    public ImmutableMap<String, Object> schema(String hdfs) throws Exception {
        Schema schema = HoodieUtils.getSchema(hdfs);
        return mapper.readValue(schema.toString(), new TypeReference<ImmutableMap<String, Object>>() {
        });
    }
}
