package com.energy.manage.service.util;

import com.energy.manage.service.property.analysis.AlgorithmProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author chy
 * @date 2024/7/9 14:08
 * @desc
 */
public class NetUtils {


    /**
     * 内网前缀
     */
    private final static String INTRANET_PREFIX = "192.168";

    /**
     * 内网前缀
     */
    private final static String LOCAL_PREFIX = "127.0.0";

    /**
     * ip:port 正则
     */
    public final static String IP_PORT_REGEX = "^(http[s]?://)?([^:/\\s]+)(:)+[0-9]{1,}/";

    /**
     * 协议
     */
    private static final String FILE_ADDR_FREFIX = "http://";


//    private static AlgorithmProperties algorithmProperties;


    /**
     * 判断当前host 是否是内网
     * @param ip
     * @return
     */
    public static boolean isIntranet(String ip) {
        if(StringUtils.isBlank(ip)){
            return false;
        }
        ip.replace("http://","").replace("https://","");
        return StringUtils.startsWithAny(ip,INTRANET_PREFIX,LOCAL_PREFIX);
    }

    /**
     * 根据url获取IP地址与端口号
     * @param url
     * @return
     */
    public static String getIpAndPort(String url){
        if(StringUtils.isBlank(url)){
            return null;
        }
        Pattern p = Pattern.compile(IP_PORT_REGEX);
        Matcher matcher = p.matcher(url);
        return matcher.find() ? matcher.group() : null ;
    }

    /**
     * 获取分析结果文件地址前缀并替换或添加
     * @param isIntranet
     * @param fileAddr
     * @return
     */
    public static String getFilePath(boolean isIntranet,String fileAddr){
        AlgorithmProperties algorithmProperties = SpringTools.getApplicationContext().getBean(AlgorithmProperties.class);
        String minIoIpPort = isIntranet ? algorithmProperties.getAnalysisFileIntranetAddr() : algorithmProperties.getAnalysisFileExternalAddr();
        //数据兼容
        if(StringUtils.startsWith(fileAddr,FILE_ADDR_FREFIX)){
            return fileAddr.replace(NetUtils.getIpAndPort(fileAddr),minIoIpPort);
        }
        return minIoIpPort + fileAddr;
    }

}
