package com.jianrmod.plugins.harmony.Tools;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.Environment;
import android.os.Handler;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.kaopiz.kprogresshud.KProgressHUD;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.util.Collections;
import java.util.List;


/**
 * Created by 58381 on 2018/1/20.
 */

public class Utils {
    private static final String TAG = "Utils";
    public static Handler handler;
    public static int getPixelsFromDp(Activity activity, int size) {
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        return (size * metrics.densityDpi) / DisplayMetrics.DENSITY_DEFAULT;
    }

    public static DisplayMetrics getMetrics(Activity activity) {
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        return metrics;
    }

    public static void toast(Context context, final String str) {
        final Context finalContext = context;
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(finalContext, str, Toast.LENGTH_LONG).show();
            }
        });

    }

    public static void setImmersion(Activity activity) {
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    }

    public static String getSDCardPath(Context context) {
        String path =context.getFilesDir() + "/";
        return path;
    }

    public static String getAppPath(Context context) {
        String path =context.getFilesDir() + "/jianRMG";
        return path;
    }



    public static <T> List<T> ListRemoveNull(List<T> list) {
        list.removeAll(Collections.singleton(null));
        return list;
    }

    public static KProgressHUD showLoading(Context context, String title, String text) {
        if (text == null) {
            text = "载入中";
        }
        if (title == null) {
            title = "请稍后";
        }
        KProgressHUD hud = KProgressHUD.create(context)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel(title)
                .setDetailsLabel(text)
                .setCancellable(false)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f);
        return hud;
    }

    public static boolean testStringIsNull(String... strings) {
        for (String string : strings) {
            if (null == string || "".equals(string) || string.length() == 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 复制单个文件
     *
     * @param srcFileName  待复制的文件名
     * @param destFileName 目标文件名
     * @param overlay      如果目标文件存在，是否覆盖
     * @return 如果复制成功返回true，否则返回false
     */
    public static boolean copyFile(String srcFileName, String destFileName,
                                   boolean overlay) {
        File srcFile = new File(srcFileName);
        String MESSAGE = "";
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            MESSAGE = "源文件：" + srcFileName + "不存在！";
            Log.i(TAG, MESSAGE);
            return false;
        } else if (!srcFile.isFile()) {
            MESSAGE = "复制文件失败，源文件：" + srcFileName + "不是一个文件！";
            Log.i(TAG, MESSAGE);
            return false;
        }

        // 判断目标文件是否存在
        File destFile = new File(destFileName);
        // 如果目标文件所在目录不存在，则创建目录
        Log.i(TAG, "目标文件夹：" + destFileName + " exists:" + destFile.exists());
        if (!destFile.exists()) {
            // 目标文件所在目录不存在
            Log.i(TAG, "目标文件所在目录不存在" + destFile.getAbsolutePath());
            if (!destFile.mkdirs()) {
                // 复制文件失败：创建目标文件所在目录失败
                Log.i(TAG, " 复制文件失败：创建目标文件所在目录失败:" + destFileName);
                return false;
            }

        }

        // 复制文件
        int byteread = 0; // 读取的字节数
        InputStream in = null;
        OutputStream out = null;

        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(destFile + "/" + srcFile.getName());
            byte[] buffer = new byte[1024];

            while ((byteread = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteread);
            }
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean writerFile(String srcFile, String data) {
        File file = new File(srcFile);
        File path=new File(file.getAbsolutePath().split(file.getName())[0]);
        if (!path.exists()) {
           path.mkdirs();
        }
        try {
            PrintWriter writer = new PrintWriter(file);
            writer.write(data);
            writer.flush();
            writer.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String readFile(String srcFile) {
        File file = new File(srcFile);
        if (!file.exists()) {
            return null;
        }
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String tmp, str = "";
            while ((tmp = reader.readLine()) != null) {
                str += tmp;
            }
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void deleteFiles(String path) {
        File files = new File(path);
        if (files.exists()) {
            if (files.isDirectory()) {
                for (File file : files.listFiles()) {
                    deleteFiles(file.getAbsolutePath());
                }
            }
            files.delete();
        }
    }

    public static boolean getApplicationPackName(Context context, String packName) {
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
        for (PackageInfo info : packages) {
            if (info.packageName.equals(packName)) {
                return true;
            }
        }
        return false;
    }

    public static String getFileMD5(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;
        }
        return bytesToHexString(digest.digest());
    }

    public static String getMD5(String data) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(data.getBytes());
            return bytesToHexString(digest.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (byte aSrc : src) {
            int v = aSrc & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }



    static String[] Base64Encode(File file) {
        try {
            DataInputStream inputStream = new DataInputStream(new FileInputStream(file));
            byte[] b = new byte[inputStream.available()];
            while ((inputStream.read(b)) != -1) {
            }
            inputStream.close();
            return new String(Base64.encode(b, Base64.DEFAULT)).split("\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    static void Base64Decode(String base64, File file) {
        try{
            byte[] b=Base64.decode(base64,Base64.DEFAULT);
            if(!file.exists()){
                file.createNewFile();
            }
            FileOutputStream outputStream=new FileOutputStream(file);
            outputStream.write(b);
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
   public static boolean readClientVersionIsbigzhao(Context context){
        SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);
        return sp.getString("magicVersion", "com.bigzhao.jianrmagicbox").equals("com.bigzhao.jianrmagicbox");
    }

    public static void changeClientVersion(boolean b,Context context) {
        try {
            if(b){
                context.getClassLoader().loadClass("com.yutou.jianr_mg.Data.AppData").getField("magicPackageName").set(null,"com.huanmeng.zhanjian2");
            }else{
                context.getClassLoader().loadClass("com.yutou.jianr_mg.Data.AppData").getField("magicPackageName").set(null,"ccom.bigzhao.jianrmagicbox");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
