package com.xm.test.myfilemaster.ad

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.hardware.Sensor
import android.hardware.SensorManager
import android.net.ConnectivityManager
import android.net.Proxy
import android.os.BatteryManager
import android.os.Build
import android.telephony.TelephonyManager
import android.text.TextUtils
import java.io.DataOutputStream
import java.io.File
import java.lang.reflect.Method


object KokoReportHelper {


    //https://blog.51cto.com/u_16213304/7913939
    //是否root
    /**
     * 通过Path判断是否root
     */
    fun isPathRooted(): Boolean {
        val paths = arrayOf("/system/bin/", "/system/xbin/", "/su/bin/", "/sbin/", "/su/")
        for (path in paths) {
            if (File(path + "su").exists()) {
                return true
            }
        }
        return false
    }

    /**
     * 通过执行shell命令来判断设备是否已经root
     */
    fun isShellRooted(): Boolean {
        try {
            val process = Runtime.getRuntime().exec("su")
            val os = DataOutputStream(process.outputStream)
            os.writeBytes("echo root\n")
            os.writeBytes("exit\n")
            os.flush()
            process.waitFor()
            if (process.exitValue() == 0) {
                return true
            }
        } catch (e: Exception) {
//            e.printStackTrace()
        }
        return false
    }

    /**
     * 是否是虚拟机
     * https://blog.51cto.com/u_16175492/7712954
     * 检查当前设备的信息，包括设备型号、产品名称、品牌、硬件等
     */
    fun isVirtualMachine(): Boolean {
        val manufacturer = Build.MANUFACTURER
        val model = Build.MODEL
        val product = Build.PRODUCT
        return if (manufacturer.contains("Genymotion") || model.contains("Emulator") || product.contains("sdk")) {
            true
        } else false
    }

    /**
     * 是否插sim卡
     */
    fun isSimCardInserted(context: Context): Boolean {
        val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        return telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY
    }


    /**
     * 是否有代理
     * 判断设备 是否使用代理上网
     * https://blog.csdn.net/verynewbeee/article/details/135698990
     */
    @SuppressLint("ObsoleteSdkInt")
    fun isWifiProxy(context: Context?): Boolean {
        val IS_ICS_OR_LATER = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH
        val proxyAddress: String
        val proxyPort: Int
        if (IS_ICS_OR_LATER) {
            proxyAddress = System.getProperty("http.proxyHost") ?: ""
            val portStr = System.getProperty("http.proxyPort")
            proxyPort = (portStr ?: "-1").toInt()
        } else {
            proxyAddress = Proxy.getHost(context)
            proxyPort = Proxy.getPort(context)
        }
        return !TextUtils.isEmpty(proxyAddress) && proxyPort != -1
    }

    /**
     *  是否开启vpn
     * https://cloud.tencent.com/developer/ask/2122015
     */
    @SuppressLint("ObsoleteSdkInt")
    fun isVpnConnected(context: Context): Boolean {
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val networkInfo = cm.activeNetworkInfo
            if (networkInfo != null) {
                return networkInfo.type == ConnectivityManager.TYPE_VPN
            }
        } else {
            // 低版本 Android 系统可能需要使用其他方法检测 VPN 连接
        }
        return false
    }


    /**
     * 开发者模式是否开启
     *
     * 检测是否开启动了usb 调试模式
     */
    @SuppressLint("PrivateApi")
    fun isEnableDeveloperDebug(context: Context): Boolean {
        var adb = ""
        try {
            val clazz = Class.forName("android.os.SystemProperties")
            val get: Method = clazz.getMethod("get", String::class.java, String::class.java)
            adb = get.invoke(clazz, "persist.sys.usb.config", "")?.toString() ?: ""
        } catch (e: java.lang.Exception) {

        }
        return adb == "adb"
    }

    /**
     * 是否在充电
     * https://blog.csdn.net/su749520/article/details/83898354
     */
    fun isCharging(context: Context): Boolean {
        val batteryBroadcast = context.registerReceiver(
            null,
            IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        )
        // 0 means we are discharging, anything else means charging
        val isCharging = batteryBroadcast!!.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) != 0
        return isCharging
    }


    /**
     * 获取手机中所有app列表
     * 获取所有带有桌面属性的APK
     */
    @SuppressLint("QueryPermissionsNeeded")
    fun getAllLauncherAppPackage(context: Context): List<String> {

        val intent = Intent().apply {
            action = Intent.ACTION_MAIN
            addCategory(Intent.CATEGORY_LAUNCHER)
        }

        val resolveInfos = context.packageManager.queryIntentActivities(
            intent, PackageManager.MATCH_ALL
        )

        return resolveInfos.map { it.activityInfo.packageName }
    }


    /**
     * 是否支持重力传感器
     */
    fun isSupportAccelerometer(context: Context): Boolean {
        val sensorManager: SensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        val sensorAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        return sensorAccelerometer != null
    }

    fun isHooked(): Int {
        try {
            // 检测Xposed
            Class.forName("de.robv.android.xposed.XposedBridge")
            return 1
        } catch (e: ClassNotFoundException) {
            // 忽略异常
        }
        try {
            // 检测Frida
            Class.forName("com.android.server.frida.Server")
            return 1
        } catch (e: ClassNotFoundException) {
            // 忽略异常
        }

        // 检测Substrate
        if (File("/data/local/tmp/inject").exists()) {
            return 1
        }
        return 0
    }
}







