package com.uiui.zyappstore.utils;

import android.content.Context;
import android.util.Log;

import com.arialyy.aria.core.Aria;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.MessageDigest;

public class FileUtils {
    public static String getFileNamefromURL(String url) {
        int position = url.lastIndexOf("/");
        return url.substring(position + 1);
    }

    public static String getMD5fromFileName(String fileName) {
        int position = fileName.lastIndexOf("/");
        return fileName.substring(position + 9, fileName.length() - 4);
    }

    /**
     * 获取单个文件的MD5值
     *
     * @param file 文件
     * @return
     */

    public static String getFileMD5s(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(32);
    }

    public static void ariaDownload(Context context, String url, JsonObject jsonObject) {
        String fileName = getFileNamefromURL(url);
        JsonElement jsonElement = jsonObject.get("MD5");
        if (jsonElement != null) {
            String urlMD5 = jsonElement.getAsString();
            Log.e("ariaDownload", "urlMD5=" + urlMD5);
        }
        File file = new File(JGYUtils.getInstance().getDownLoadPath());
        if (file.exists() && !file.isDirectory()) {
            String filenameMD5 = getMD5fromFileName(url);

            String fileMD5 = FileUtils.getFileMD5s(file);
            Log.e("ariaDownload", "filenameMD5=" + filenameMD5);
            Log.e("ariaDownload", "fileMD5=" + fileMD5);
            //后端还没有完成json字段的MD5，暂时用文件名获取
            if (fileMD5.equalsIgnoreCase(filenameMD5)) {
                ApkUtils.installApp(context, file.getAbsolutePath());
            } else {
                Aria.download(context)
                        .load(url)     //读取下载地址
                        .setFilePath(JGYUtils.getInstance().getDownLoadPath() + fileName)
                        .ignoreFilePathOccupy()
                        .setExtendField(jsonObject.toString())
                        .create();   //启动下载}
            }
        } else {
            Aria.download(context)
                    .load(url)     //读取下载地址
                    .setFilePath(JGYUtils.getInstance().getDownLoadPath() + fileName)
                    .ignoreFilePathOccupy()
                    .setExtendField(jsonObject.toString())
                    .create();   //启动下载}
        }
    }

    /**
     * 格式化文件大小
     *
     * @param size file.length() 获取文件大小
     */
    public static String formatFileSize(double size) {
        if (size < 0) {
            return "0kb";
        }
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "b";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }
}
