package com.sheep.gamegroup.util;

import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by realicing on 2018/10/22.
 * realicing@sina.com
 */
public class Md5Util {

    private static final String TAG = "Md5Util";

    /**
     * 创建文件名，如果url链接有后缀名，则使用url中的后缀名
     *
     * @return url 的 hashKey
     */
    public static String createFileName(String url) {
        int end = url.indexOf("?");
        String tempUrl, fileName = "";
        if (end > 0) {
            tempUrl = url.substring(0, end);
            int tempEnd = tempUrl.lastIndexOf("/");
            if (tempEnd > 0) {
                fileName = tempUrl.substring(tempEnd + 1, tempUrl.length());
            }
        } else {
            int tempEnd = url.lastIndexOf("/");
            if (tempEnd > 0) {
                fileName = url.substring(tempEnd + 1, url.length());
            }
        }
        return fileName;
    }


    /**
     * 获取字符串的md5
     *
     * @return 字符串为空或获取md5失败，则返回""
     */
    public static String getStrMd5(String str) {
        if (TextUtils.isEmpty(str)) return "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            return new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
        }
        return "";
    }

    /**
     * 校验文件MD5码
     */
    public static boolean checkMD5(File firstFile, File updateFile) {
        if (firstFile == null || updateFile == null) {
            Log.e(TAG, "MD5 string empty or updateFile null");
            return false;
        }

        String firstCalculatedDigest = getFileMD5(firstFile);
        String calculatedDigest = getFileMD5(updateFile);
        if (firstCalculatedDigest == null) {
            Log.e(TAG, "firstCalculatedDigest null");
            return false;
        }
        if (calculatedDigest == null) {
            Log.e(TAG, "calculatedDigest null");
            return false;
        }
        return calculatedDigest.equalsIgnoreCase(firstCalculatedDigest);
    }
    /**
     * 校验文件MD5码
     */
    public static boolean checkMD5(String md5, File updateFile) {
        if (TextUtils.isEmpty(md5) || updateFile == null) {
//            ALog.e(TAG, "MD5 string empty or updateFile null");
            return false;
        }

        String calculatedDigest = getFileMD5(updateFile);
        if (calculatedDigest == null) {
//            ALog.e(TAG, "calculatedDigest null");
            return false;
        }
        return calculatedDigest.equalsIgnoreCase(md5);
    }

    /**
     * 校验文件MD5码
     */
    public static boolean checkMD5(String md5, InputStream is) {
        if (TextUtils.isEmpty(md5) || is == null) {
//            ALog.e(TAG, "MD5 string empty or updateFile null");
            return false;
        }

        String calculatedDigest = getFileMD5(is);
        if (calculatedDigest == null) {
//            ALog.e(TAG, "calculatedDigest null");
            return false;
        }
        return calculatedDigest.equalsIgnoreCase(md5);
    }

    /**
     * 获取文件MD5码
     */
    public static String getFileMD5(File updateFile) {
        InputStream is;
        try {
            is = new FileInputStream(updateFile);
        } catch (FileNotFoundException e) {
//            ALog.e(TAG, e);
            return null;
        }

        return getFileMD5(is);
    }

    /**
     * 获取文件MD5码
     */
    public static String getFileMD5(InputStream is) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
//            ALog.e(TAG, e);
            return null;
        }

        byte[] buffer = new byte[8192];
        int read;
        try {
            while ((read = is.read(buffer)) > 0) {
                digest.update(buffer, 0, read);
            }
            byte[] md5sum = digest.digest();
            BigInteger bigInt = new BigInteger(1, md5sum);
            String output = bigInt.toString(16);
            // Fill to 32 chars
            output = String.format("%32s", output).replace(' ', '0');
            return output;
        } catch (IOException e) {
            throw new RuntimeException("Unable to process file for MD5", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
//                ALog.e(TAG, e);
            }
        }
    }

}
