package com.jld.vod.utils;

import android.app.ActivityManager;
import android.app.backup.BackupManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import java.io.File;
import java.lang.reflect.Method;
import java.util.Locale;

public class AppUtil {
    /**
     * 判断服务是否运行
     *
     * @param service_Name:服务的包名+类名
     */
    public static boolean isServiceRunning(Context context, String service_Name) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (service_Name.equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    /**
     * 设置文本信息
     *
     * @param content ：显示的文本；
     */
    public static void setText(TextView textView, String content) {
        if (textView == null) return;
        if (TextUtils.isEmpty(content)) return;
        textView.setText(content);
    }

    /**
     * 吐司
     *
     * @param context           ：上下文；
     * @param messageId:吐司内容Id；
     */
    public static void ShowToast(Context context, int messageId) {
        if (context == null) return;
        Toast.makeText(context, messageId, Toast.LENGTH_SHORT).show();
    }

    public static void setBgColor(Context context, View parent, int color) {
        if (parent == null || context == null) return;
        parent.setBackgroundColor(ContextCompat.getColor(context, color));
    }
    /**
     * 设置控件显示和隐藏
     */
    public static void setVisible(View view, int visible) {
        if (view == null) return;
        if (view.getVisibility() == visible) return;
        view.setVisibility(visible);
    }
    /**
     * 吐司
     *
     * @param context       ：上下文；
     * @param message:吐司内容；
     */
    public static void ShowToast(Context context, String message) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }


    public static long getVersionCode(Context context) {

        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo  = packageManager.getPackageInfo(context.getPackageName(),0);
            return  packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return -1;
    }

    /**
     * 获取sn码
     * @return
     */
    public static String getDeviceSN() {
        String serial = null;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, "ro.serialno");
            Log.i("serial",serial);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serial;
    }

    /**
     * 跳转apk
     * @param mContext
     * @param packagename
     */
    public static boolean openAPK(Context mContext,String packagename)
    {
        try {
            PackageManager packageManager = mContext.getPackageManager();
            Intent intent= packageManager.getLaunchIntentForPackage(packagename);
            if (intent == null)
            {
                Toast.makeText(mContext,"This app is not installed",Toast.LENGTH_LONG).show();
                return false;
            }else{
                mContext.startActivity(intent);
                return true;
            }

        }catch (Exception e)
        {
            Toast.makeText(mContext,"APP open failed",Toast.LENGTH_LONG).show();
            return false;
        }
    }

    /**
     * 采用了新的办法获取APK图标，之前的失败是因为android中存在的一个BUG,通过
     * appInfo.publicSourceDir = apkPath;来修正这个问题，详情参见:
     * http://code.google.com/p/android/issues/detail?id=9151
     */
    public static String getApkPackName(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath,
                PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;
            appInfo.sourceDir = apkPath;
            appInfo.publicSourceDir = apkPath;
            try {
                return appInfo.packageName;
            } catch (OutOfMemoryError e) {
                Log.e("ApkIconLoader", e.toString());
            }
        }
        return null;
    }
    public static void setLocale(Locale locale)
    {

        try {
            Class iActivityManager = Class.forName("android.app.IActivityManager");
            Class activityManagerNative = Class.forName("android.app.ActivityManagerNative");
            Method getDefault = activityManagerNative.getDeclaredMethod("getDefault");
            Object objIActMag = getDefault.invoke(activityManagerNative);
            Method getConfiguration = iActivityManager.getDeclaredMethod("getConfiguration");
            Configuration config = (Configuration) getConfiguration.invoke(objIActMag);
            config.locale = locale;
            Class clzConfig = Class.forName("android.content.res.Configuration");
            java.lang.reflect.Field userSetLocale = clzConfig.getField("userSetLocale");
            userSetLocale.set(config, true);
            Class[] clzParams = {Configuration.class};
            Method updateConfiguration = iActivityManager.getDeclaredMethod("updateConfiguration", clzParams);
            updateConfiguration.invoke(objIActMag, config);
            BackupManager.dataChanged("com.android.providers.settings");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }
}
