package com.fs.watch.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.InputStream;
import java.math.BigInteger;
import java.net.URL;
import java.security.MessageDigest;

public class MD5Utils {
    public static String  getFileMD5FromURL(String fileUrl) {
        try (InputStream is = new URL(fileUrl).openStream()) {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int bytesRead;

            while ((bytesRead = is.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }

            byte[] digest = md.digest();
            // 转换为 32 位小写十六进制字符串
            return String.format("%032x", new BigInteger(1, digest));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 计算文件 MD5 并返回字节数和 MD5 值
    public static JSONObject getMd5AndSizeFromUrl(String fileUrl) {
        JSONObject result = new JSONObject();
        try (InputStream is = new URL(fileUrl).openStream()) {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int bytesRead;
            long totalSize = 0;

            while ((bytesRead = is.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
                totalSize += bytesRead;
            }

            byte[] digest = md.digest();
            String md5 = String.format("%032x", new BigInteger(1, digest));
            result.put("md5", md5);
            result.put("size", totalSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
