package com.lanyuanxiaoyao.service.hudi.service;

import cn.hutool.core.util.ObjectUtil;
import com.lanyuanxiaoyao.service.common.entity.TableMeta;
import com.lanyuanxiaoyao.service.forest.service.InfoService;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hudi.common.table.HoodieTableMetaClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author lanyuanxiaoyao
 * @date 2024-01-24
 */
@Service
public class HdfsService {
    private static final Logger logger = LoggerFactory.getLogger(HdfsService.class);

    private final InfoService infoService;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    public HdfsService(InfoService infoService) {
        this.infoService = infoService;
    }

    @Cacheable(value = "exists-hudi-table", sync = true, key = "#flinkJobId.toString()+#alias")
    public Boolean existsHudiTable(Long flinkJobId, String alias) {
        try {
            TableMeta meta = infoService.tableMetaDetail(flinkJobId, alias);
            if (ObjectUtil.isNotNull(meta)) {
                return existsHudiTable(meta.getHudi().getTargetHdfsPath());
            }
        } catch (Throwable ignored) {
        }
        return false;
    }

    @Cacheable(value = "exists-hudi-table", sync = true)
    public Boolean existsHudiTable(String hdfs) {
        if (!existsPath(hdfs)) {
            return false;
        }
        try {
            HoodieTableMetaClient.builder()
                    .setConf(new Configuration())
                    .setBasePath(hdfs)
                    .build();
            return true;
        } catch (Throwable ignored) {
        }
        return false;
    }

    @Cacheable(value = "exists-path", sync = true)
    public Boolean existsPath(String hdfs) {
        try(FileSystem fileSystem = FileSystem.get(new Configuration())) {
            return fileSystem.exists(new Path(hdfs));
        } catch (IOException ignored) {
        }
        return false;
    }
}
