package com.yutou.jianr_mg.Tools;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.yutou.jianr_mg.Application;
import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Data.MGamePackname;
import com.yutou.jianr_mg.Data.TModfilePath;
import com.yutou.jianr_mg.Interfaces.HttpInterface;
import com.yutou.jianr_mg.Network.HttpApi;
import com.yutou.jianr_mg.Network.HttpUtils;
import com.yutou.jianr_mg.R;
import com.yutou.jianr_mg.views.WebActivity;

import org.json.JSONObject;

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 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, String str) {
        if (context == null)
            context = Application.application;
        Context finalContext = context;
        AppData.handler.post(() -> 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() {
        String path = Environment.getExternalStorageDirectory().getPath() + "/";
        return path;
    }

    public static String getAppPath() {
        String path = Environment.getExternalStorageDirectory().getPath() + "/jianRMG";
        return path;
    }

    private static DisplayImageOptions initDisplayOptions() {
        DisplayImageOptions.Builder displayImageOptionsBuilder = new DisplayImageOptions.Builder();
        displayImageOptionsBuilder.cacheInMemory(false);
        displayImageOptionsBuilder.cacheOnDisk(true);
        displayImageOptionsBuilder.showImageForEmptyUri(R.drawable.ic_launcher_background);
        return displayImageOptionsBuilder.build();
    }

    public static ImageLoader initImageLoader(Context context) {

        ImageLoader imageLoader = ImageLoader.getInstance();
        ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(context);
        File cachePath = new File(getAppPath() + "/cache/");
        if (!cachePath.exists()) {
            cachePath.exists();
        }
        //builder.memoryCache(new WeakMemoryCache());
        builder.diskCache(new UnlimitedDiskCache(cachePath));
        builder.defaultDisplayImageOptions(initDisplayOptions());

        imageLoader.init(builder.build());
        return imageLoader;
    }

    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) {
            System.out.println("被检测的包名:" + packName + " 当前包名：" + info.packageName);
            if (info.packageName.equals(packName)) {
                return true;
            }
        }
        return false;
    }

    public static void initGamePackName() {
        try {
            HttpUtils.get(HttpApi.HOME_URL + HttpApi.MOD_GAME_PACKNAME, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try {
                        Log.i(HttpApi.MOD_GAME_PACKNAME, string);
                        JSONObject json = new JSONObject(string);
                        AppData.packnames = JSON.parseArray(json.getJSONArray("data").toString(), MGamePackname.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void httpError(Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void initInstallPath() {
        try {
            HttpUtils.get(HttpApi.HOME_URL + HttpApi.INSTALL_PATH, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try {
                        Log.i(HttpApi.INSTALL_PATH, string);
                        JSONObject json = new JSONObject(string);
                        AppData.installPath = JSON.parseArray(json.getJSONArray("data").toString(), TModfilePath.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void httpError(Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    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();
    }

    public static void openWebView(String url) {
        if (url.equals("#")) {
            Utils.toast(Application.application, "暂无连接");
            return;
        }
        Intent intent;
        try {
            Uri uri = Uri.parse(url);
            intent = new Intent(Intent.ACTION_VIEW, uri);
        } catch (Exception e) {
            e.printStackTrace();
            intent = new Intent(Application.application, WebActivity.class);
            intent.putExtra("url", url);

        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Application.application.startActivity(intent);

    }

    public static String getIMEI() {
        String imei = "-1";
        TelephonyManager telephonyManager = (TelephonyManager) Application.application.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null && ActivityCompat.checkSelfPermission(Application.application, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            imei = telephonyManager.getDeviceId();
        }
        return imei;
    }

    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 String getVersion() {
        String versionName = null;
        try {
            PackageManager pm = Application.application.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(Application.application.getPackageName(), 0);
            versionName = pi.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    public static void removePlugins(String s) {
        File file = new File(Application.application.getFilesDir() + "/plugin/" + s + ".jar");
        if (file.exists()) {
            file.delete();
        }
        File dex = new File(Application.application.getFilesDir() + "/plugin/oat/");
        if (dex.exists()) {
            for (File listFile : dex.listFiles()) {
                if (listFile.getName().contains(s)) {
                    listFile.delete();
                }
            }
        }
        File arm = new File(Application.application.getFilesDir() + "/plugin/oat/arm/");
        if (arm.exists()) {
            for (File listFile : arm.listFiles()) {
                if (listFile.getName().contains(s)) {
                    listFile.delete();
                }
            }
        }
    }
}
