package com.lanyuanxiaoyao.service.launcher.utils;

import cn.hutool.core.util.ObjectUtil;
import com.lanyuanxiaoyao.service.launcher.configuration.HadoopConfiguration;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.list.ImmutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Hadoop 工具类
 *
 * @author ZhangJiacheng
 * @date 2022-04-25
 */
public class HadoopUtil {
    private static final Logger logger = LoggerFactory.getLogger(HadoopUtil.class);

    public static Configuration createConfiguration() throws IOException {
        return createConfiguration(null);
    }

    public static Configuration createConfiguration(HadoopConfiguration configuration) throws IOException {
        Configuration hadoopConfiguration = new Configuration();
        if (ObjectUtil.isNull(configuration)) {
            return hadoopConfiguration;
        }
        UserGroupInformation.setConfiguration(hadoopConfiguration);
        if (UserGroupInformation.isSecurityEnabled()) {
            UserGroupInformation.loginUserFromKeytab(configuration.getKerberosPrincipal(), configuration.getKerberosKeytabPath());
        }
        return hadoopConfiguration;
    }

    public static FileSystem createFileSystem() {
        return createFileSystem(null);
    }

    public static FileSystem createFileSystem(Configuration configuration) {
        try {
            if (ObjectUtil.isNull(configuration)) {
                return FileSystem.get(new Configuration());
            }
            return FileSystem.get(configuration);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static ImmutableList<FileStatus> list(FileSystem fileSystem, Path path) {
        try {
            return Lists.immutable.of(fileSystem.listStatus(path));
        } catch (IOException e) {
            logger.error("List error", e);
            return Lists.immutable.empty();
        }
    }
}
