package com.lovenav.utils;
import java.io.BufferedReader;

import com.alibaba.fastjson2.JSON;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import javax.net.ssl.HttpsURLConnection;

public class UrlCheckUtil {

    /**
     * 判断链接是否有效
     * 输入链接
     * 返回true或者false
     */
    public static boolean isUrlValid(String strLink) {
        URL url;
        try {
            url = new URL(strLink);
            HttpURLConnection connt = (HttpURLConnection)url.openConnection();
            connt.setRequestMethod("HEAD");
            String strMessage = connt.getResponseMessage();
            if (strMessage.compareTo("Not Found") == 0) {
                return false;
            }
            connt.disconnect();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 判断链接是否有效
     * 输入链接
     */
    public static String checkUrlConnection(String url) {
        // 创建http POST请求
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json");
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(600)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(1000)// 设置连接请求超时时间
                .setSocketTimeout(1000)// 设置读取数据连接超时时间
                .build();
        // 为httpPost实例设置配置
        httpGet.setConfig(requestConfig);
        // 设置请求头
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        int statusCode = 404;
        try {
            httpclient = HttpClients.createDefault();// 创建Httpclient对象
            response = httpclient.execute(httpGet);// 执行请求
            statusCode = response.getStatusLine().getStatusCode();
        }catch (SocketException e) {
            return "404";
        } catch (IOException e) {
            System.out.println("报错");
            return "404";
        }
        return String.valueOf(statusCode);
    }

    /**
     * 检查http连接
     */
    public static boolean CheckHttp(String address) throws URISyntaxException, MalformedURLException {
        URL url = new URL(address);
        URI uri = url.toURI();
        System.out.println(uri.getScheme());
        if(uri.getScheme().equals("https")){
            return true;
        }else
            return false;
    }

    /**
     * 发送GET请求
     */
    public static String sendGetRequest(String url) throws IOException {
        URL requestUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setRequestMethod("GET");

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            return response.toString();
        } else {
            throw new RuntimeException("HTTP GET request failed with response code: " + responseCode);
        }
    }

    public static String url_speed(String url) {
        String url_check = url;
        int numRequests = 10;
        long totalResponseTime = 0;

        for (int i = 0; i < numRequests; i++) {
            long startTime = System.currentTimeMillis();
            try {
                UrlCheckUtil.sendGetRequest(url_check);
                long endTime = System.currentTimeMillis();
                long responseTime = endTime - startTime;
                totalResponseTime += responseTime;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        double averageResponseTime = (double) totalResponseTime / (1 * numRequests);
        return JSON.toJSONString(averageResponseTime + " ms");
    }
}
