package com.persagy.dmp.storage.config;

import com.persagy.dmp.common.constant.ResponseCode;
import com.persagy.dmp.common.exception.BusinessException;
import com.persagy.dmp.storage.service.IFileStorageService;
import com.persagy.dmp.storage.service.impl.HdfsStorageServiceImpl;
import com.persagy.dmp.storage.service.impl.MinioStorageServiceImpl;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.annotation.PostConstruct;
import java.io.IOException;

/**
 * MinIO配置
 * @author Charlie Yu
 * @date 2021-05-15
 */
@Configuration
@ConfigurationProperties(prefix = "persagy.common.file")
@Data
@Slf4j
public class HdfsConfig {

    /**jar同级config目录下的位置*/
    private static final String FILE_CONFIG_PATH="file:./config/";
    /**Classpath位置*/
    private static final String FILE_CLASSPATH_PATH="classpath:./";
    /**hdfs-site.xml文件名称*/
    private static final String HDFS_SITE_FILE_NAME ="hdfs-site.xml";
    /**core-site.xml文件名称*/
    private static final String HDFS_CORE_FILE_NAME ="core-site.xml";
    /**hdfs访问地址*/
    private static final String HDFS_URL_KEY="fs.defaultFS";
    /**hdfs访问用户名*/
    private static final String HADOOP_USER_NAME="HADOOP_USER_NAME";

    /** 文件服务器url */
    private String url;
    /** 文件服务器accessKey */
    private String accessKey;
    /** 文件服务器secretKey */
    private String secretKey;

    @Bean
    @ConditionalOnProperty(value = "persagy.common.file.storage", havingValue = "2")
    public org.apache.hadoop.conf.Configuration plainConfig() {
        org.apache.hadoop.conf.Configuration plainConfig = new org.apache.hadoop.conf.Configuration();
        try {
            System.setProperty(HADOOP_USER_NAME,accessKey);
            String hbaseSiteConfigFilePath = FILE_CONFIG_PATH+ HDFS_SITE_FILE_NAME;
            String hbaseSiteClasspathFilePath = FILE_CLASSPATH_PATH+ HDFS_SITE_FILE_NAME;
            String hbaseCoreConfigFilePath = FILE_CONFIG_PATH+ HDFS_CORE_FILE_NAME;
            String hbaseCoreClasspathFilePath = FILE_CLASSPATH_PATH+ HDFS_CORE_FILE_NAME;
            log.info("hdfs-site.xml文件存在情况,config目录:{},classPath:{}",checkResoucesExist(hbaseSiteConfigFilePath),
                    checkResoucesExist(hbaseSiteClasspathFilePath));
            log.info("core-site.xml文件存在情况,config目录:{},classPath:{}",checkResoucesExist(hbaseCoreConfigFilePath),
                    checkResoucesExist(hbaseCoreClasspathFilePath));
            log.info("classpath下的文件是否存在:"+checkResoucesExist(hbaseSiteClasspathFilePath));
            // 导入hbase-site.xml文件
            Resource[] siteResources = getResource(hbaseSiteConfigFilePath, hbaseSiteClasspathFilePath);
            if (siteResources.length<1){
                throw new BusinessException(ResponseCode.B0300.getCode(),"hdfs-site.xml文件不存在");
            }
            // 导入hbase-core.xml文件
            Resource[] coreResources = getResource(hbaseCoreConfigFilePath, hbaseCoreClasspathFilePath);
            if (coreResources.length<1){
                throw new BusinessException(ResponseCode.B0300.getCode(),"core-site.xml文件不存在");
            }
            plainConfig.set(HDFS_URL_KEY,url);
            Resource siteResource = siteResources[0];
            plainConfig.addResource(siteResource.getInputStream());
            Resource coreResource = coreResources[0];
            plainConfig.addResource(coreResource.getInputStream());
        }catch (Exception e) {
            log.error("加载HDFS配置文件失败!",e);
        }
        return plainConfig;
    }

    @Bean
    @ConditionalOnProperty(value = "persagy.common.file.storage", havingValue = "2")
    public IFileStorageService hdfsStorageServiceImpl() {
        return new HdfsStorageServiceImpl(plainConfig());
    }

    /***
     * @Description: 校验资源文件是否存在
     * @param configFilePath : jar包同级目录下的配置文件
     * @return : com.alibaba.fastjson.JSONArray
     * @author: lijie
     * @Date:2020/6/6 19:43
     * Update By lijie 2020/6/6 19:43
     */
    private static boolean checkResoucesExist(String configFilePath) throws IOException {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resolverResources = resolver.getResources(configFilePath);
        if (resolverResources.length > 0 && resolverResources[0].exists()){
            return true;
        }
        return false;
    }

    /***
     * Description: 获取资源文件方法
     * @param configFilePath : 配置文件路径
     * @param classpathFilePath : classpath下的文件
     * @return : org.springframework.core.io.Resource[]
     * @author : lijie
     * @date :2021/3/1 14:25
     * Update By lijie 2021/3/1 14:25
     */
    public static Resource[] getResource(String configFilePath, String classpathFilePath)
            throws IOException {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resolverResources = resolver.getResources(configFilePath);
        if (resolverResources.length > 0) {
            boolean exist = true;
            for (Resource resource : resolverResources) {
                if (!resource.exists()) {
                    exist = false;
                    break;
                }
            }
            if(exist) {
                return resolverResources;
            }
        }
        return resolver.getResources(classpathFilePath);
    }

}
