package com.sobot.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 检测网络 和 sdcard的使用
 */
public class SobotSystemUtils {
    /**
     * 检测Sdcard是否存在
     *
     * @return
     */
    public static boolean isExitsSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }

    /**
     * 获取存储位置
     *
     * @return
     */
    public static String getSDCardRootPath(Context context) {
        String path;
        if (isExitsSdcard()) {
            //SD卡已装入
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                //  /storage/emulated/0/sobot/******/cache/
                path = getRootDir(context) + File.separator;
            } else {
                //  /storage/emulated/0/Android/data/******/files/Download/cache/
                path = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator + CACHE_DIR + File.separator;
            }
            SobotLogUtils.i("SD卡已装入 存储路径：" + path);
        } else {
            //外部存储不可用
            path = context.getFilesDir().getPath() + File.separator + "sobot";
            SobotLogUtils.i("外部存储不可用 存储路径：" + path);
        }
        return path;
    }

    private static final String ROOT_DIR = "sobot";
    private static final String CACHE_DIR = "cache";

    public static String getRootDir(Context mContext) {
        String packageName = mContext != null ? mContext.getPackageName() : "";
        String mRootPath = Environment.getExternalStorageDirectory().getPath() + File.separator + ROOT_DIR + File.separator + encode(packageName + File.separator + "cache");
        return mRootPath;
    }

    /**
     * 获取私有目录
     *
     * @param context
     * @return
     */
    public static String getPrivatePath(Context context) {
        return context.getFilesDir().getPath();
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static int getVersion(Context context) {
        PackageManager manager = context.getPackageManager();
        PackageInfo info;
        try {
            info = manager.getPackageInfo(context.getPackageName(), 0);
            int version = info.versionCode;
            return version;
        } catch (NameNotFoundException e) {
            // e.printStackTrace();
        }
        return 0;

    }

    /**
     * 获取包名的名称
     *
     * @param context
     * @return
     */
    public static String getPackageName(Context context) {
        PackageManager manager = context.getPackageManager();
        PackageInfo info;
        try {
            info = manager.getPackageInfo(context.getPackageName(), 0);
            String pageName = info.packageName;
            return pageName;
        } catch (NameNotFoundException e) {
            // e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取版本名称
     *
     * @return 当前应用的版本名称
     */
    public static String getVersionName(Context context) {
        PackageManager manager = context.getPackageManager();
        PackageInfo info;
        try {
            info = manager.getPackageInfo(context.getPackageName(), 0);
            String versionName = info.versionName;
            return versionName;
        } catch (Exception e) {
            // e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取应用程序名称
     */
    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /* 如果url中有中文就把中文编译一次 */
    public static String encode(String url) {
        if (url != null) {
            Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url);
            while (matcher.find()) {
                String tmp = matcher.group();
                try {
                    url = url.replaceAll(tmp, URLEncoder.encode(tmp, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return url;
    }

    public static String encodeStr(String str) {
        if (!TextUtils.isEmpty(str)) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    public static int getTargetSdkVersion(Context context) {
        int targetSdkVersion = 0;
        try {
            final PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            targetSdkVersion = info.applicationInfo.targetSdkVersion;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return targetSdkVersion;
    }


    /**
     * 获取应用的名称
     *
     * @return
     */
    public static String getApplicationName(Context context) {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = context.getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(
                    context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            applicationInfo = null;
        }
        String applicationName = "";
        if (applicationInfo != null) {
            applicationName = (String) packageManager.getApplicationLabel(applicationInfo);
        }
        return applicationName;
    }

    public static boolean inMainProcess(Context context) {
        try {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            if (am != null) {
                List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
                String mainProcessName = context.getPackageName();
                int myPid = android.os.Process.myPid();
                for (ActivityManager.RunningAppProcessInfo info : processInfos) {
                    if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            //ignor
        }
        return false;
    }
}