package com.m2pool.pool.utils;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.reflect.TypeToken;
import com.m2pool.pool.entity.BlockInfo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description TODO
 * @Date 2025/9/28 09:24
 * @Author yyb
 */
public class dome4j {
    public static void main(String[] args) throws Exception {
        getSha3xBlockInfoForXml();
    }


    public static BlockInfo getSha3xBlockInfoForXml() {
        try {
            // 从指定 URL 获取 XML 数据
            String xmlData = fetchXmlData("https://www.dxpool.com/api/address-mining/pools");
            // 移除提示信息
            BlockInfo blockInfo = extractXtmBlockInfo(xmlData);
            System.out.println(blockInfo);
            return blockInfo;

        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 从 JSON 数据中提取 id 为 30 的节点信息到 BlockInfo 中
     * @param jsonData JSON 数据字符串
     * @return BlockInfo 对象，若未找到则返回 null
     */
    private static BlockInfo extractXtmBlockInfo(String jsonData) {
        Gson gson = new Gson();
        List<XtmPoolInfo> xtmPoolInfoList = gson.fromJson(jsonData, new TypeToken<List<XtmPoolInfo>>() {}.getType());
        for (XtmPoolInfo xtmPoolInfo : xtmPoolInfoList) {
            if (xtmPoolInfo.getId() == 30) {
                BlockInfo blockInfo = new BlockInfo();
                blockInfo.setDifficulty(BigDecimal.ZERO);
                blockInfo.setHeight(xtmPoolInfo.getHeight());
                blockInfo.setPrice(new BigDecimal(xtmPoolInfo.getCoin_price()));
                // 转换单位为 H/s
                BigDecimal powerInHPerSecond = convertToHPerSecond(xtmPoolInfo.getNetwork_hashrate());
                blockInfo.setPower(powerInHPerSecond);

                blockInfo.setReward(new BigDecimal(xtmPoolInfo.getBase_reward()));
                blockInfo.setFees(new BigDecimal(xtmPoolInfo.getDefault_fee()));
                blockInfo.setProfit(BigDecimal.ZERO);
                return blockInfo;
            }
        }
        return null;
    }



    /**
     * 从指定 URL 获取 XML 数据
     * @param urlStr 目标 URL
     * @return XML 数据字符串
     * @throws IOException 网络请求异常
     */
    public static String fetchXmlData(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        //// 配置 HTTP 代理信息，需将代理地址和端口替换为实际值
        //String proxyHost = "127.0.0.1";
        //int proxyPort = 7897;
        //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        //
        //URL url = new URL(urlStr);
        //// 使用代理创建连接
        //HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
        //connection.setRequestMethod("GET");

        try (InputStream inputStream = connection.getInputStream();
             ByteArrayOutputStream result = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                result.write(buffer, 0, length);
            }
            return result.toString(String.valueOf(StandardCharsets.UTF_8));
        }
    }

    /**
     * 将带单位的哈希率转换为 H/s
     * @param hashrateStr 带单位的哈希率字符串，例如 "28.28 TH/s"
     * @return 转换为 H/s 后的 BigDecimal 数值
     */
    private static BigDecimal convertToHPerSecond(String hashrateStr) {
        // 定义正则表达式，用于匹配数值和单位
        Pattern pattern = Pattern.compile("([0-9.]+)\\s*([KMGTPEZY]?)H/s");
        Matcher matcher = pattern.matcher(hashrateStr);

        if (matcher.find()) {
            BigDecimal value = new BigDecimal(matcher.group(1));
            String unit = matcher.group(2);

            // 根据单位计算换算系数
            BigInteger multiplier;
            switch (unit) {
                case "K":
                    multiplier = BigInteger.valueOf(1000);
                    break;
                case "M":
                    multiplier = BigInteger.valueOf(1000000);
                    break;
                case "G":
                    multiplier = BigInteger.valueOf(1000000000);
                    break;
                case "T":
                    multiplier = BigInteger.valueOf(1000000000000L);
                    break;
                case "P":
                    multiplier = BigInteger.valueOf(1000000000000000L);
                    break;
                case "E":
                    multiplier = new BigInteger("1000000000000000000");
                    break;
                case "Z":
                    multiplier = new BigInteger("1000000000000000000000");
                    break;
                case "Y":
                    multiplier = new BigInteger("1000000000000000000000000");
                    break;
                default:
                    multiplier = BigInteger.ONE;
            }

            return value.multiply(new BigDecimal(multiplier));
        }

        // 如果未匹配到有效数据，返回 0
        return BigDecimal.ZERO;
    }


}
