package com.zxhyis.toolss.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.NetworkCapabilities
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
     * 0:未root，1：已root
     */
    fun isShellRooted(): Int {
        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 1
            }
        } catch (e: Exception) {
//            e.printStackTrace()
        }
        return 0
    }

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

    /**
     * 是否插sim卡

     * 0:未装，1：已装
     */
    fun isSimCardInserted(context: Context): Int {
        val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val flag = telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY
        return if (flag) 1 else 0
    }


    /**
     * 是否有代理
     * 判断设备 是否使用代理上网
     * https://blog.csdn.net/verynewbeee/article/details/135698990
     * 0：未开启代理，1：已开启代理
     */
    @SuppressLint("ObsoleteSdkInt")
    fun isProxy(context: Context?): Int {
        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)
        }
        val flag = !TextUtils.isEmpty(proxyAddress) && proxyPort != -1
        return if (flag) 1 else 0
    }

    /**
     *  是否开启vpn
     * https://cloud.tencent.com/developer/ask/2122015
     * 0：未连接VPN，1：已连接VPN
     */
    @SuppressLint("ObsoleteSdkInt")
    fun isVpnConnected(context: Context): Any {
        val cm =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val currentNetwork = cm.activeNetwork
        val networkCapabilities = cm.getNetworkCapabilities(currentNetwork)
        return if (networkCapabilities != null) {
            val flag1 = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
            val flag2 = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            if (flag1 && flag2) 1 else 0
        } else {
            0
        }
    }


    /**
     * 开发者模式是否开启
     *
     * 检测是否开启动了usb 调试模式
     * 0：未开启开发者模式，1：已开启开发者模式
     */
    @SuppressLint("PrivateApi")
    fun isEnableDeveloperDebug(context: Context): Int {
        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) {

        }
        val flag = adb == "adb"
        return if (flag) 1 else 0
    }

    /**
     * 是否在充电
     * https://blog.csdn.net/su749520/article/details/83898354
     * 0：未在充电，1：正在充电
     */
    fun isCharging(context: Context): Int {
        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 if (isCharging) 1 else 0
    }


    /**
     * 获取手机中所有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
    }

    /**
     * 0:未Hook，1：已Hook
     */
    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
    }
}







