package com.ygtx.emcs.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ToolUtils {
    public static void ping(){
        try {
            String ip = getIp(Constant.HTTP_URL);
            Process p = Runtime.getRuntime().exec("ping -w 3000 " + ip);// ping网址3次
            // 读取ping的内容，可以不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuilder stringBuffer = new StringBuilder();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
                System.out.println(content);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    public static boolean checkUrl(String urlToCheck){
        try {
            URL url = new URL(urlToCheck);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000); // Adjust timeout as needed
            connection.connect();
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public static int ping2(String ipAddress, int pingTimes, int timeOut) throws Exception{
        BufferedReader in = null;
        Runtime r = Runtime.getRuntime(); // 将要执行的ping命令,此命令是windows格式的命令
        String pingCommand = "ping -c "+pingTimes+" -i 1 -w "+timeOut+" " + ipAddress;
        try {  // 执行命令并获取输出
            Process p = r.exec(pingCommand);
            if (p == null) {
                return 0;
            }
            in = new BufferedReader(new InputStreamReader(p.getInputStream()));  // 逐行检查输出,计算类似出现=23ms TTL=62字样的次数
            float connectedCount = -1F;
            String line = null;
            int x = 0;
            while ((line = in.readLine()) != null) {
                connectedCount += getCheckResult(line);
                x = x + 1;
            }
            if(x > 0){
                connectedCount = connectedCount/x;
            }
            return Math.round(connectedCount);
        } catch (Exception ex) {
            ex.printStackTrace();  // 出现异常则返回假
            return -1;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //若line含有=18ms TTL=16字样,说明已经ping通,返回1,否則返回0.
    private static float getCheckResult(String line) {
        String time = "";
        if(line.contains("time=")){
            int ix = line.indexOf("time=");
            String startStr = line.substring(ix);
            String[] str = startStr.split(" ");
            time = str[0];
            time = time.replace("ms", "");
            time = time.replace("time=", "");
        }
        if(StringUtils.isEmpty(time)){
            return 0;
        }
        return Float.parseFloat(time);
    }

    public static String getIp(String str){
        Pattern pattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            return matcher.group();
        }
        return null;
    }
}
