package com.jishisongfu.duobibi.util

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import android.widget.Toast
import com.jishisongfu.duobibi.R

object VendorAutoStart {

    private val candidates: List<ComponentName> = listOf(
        // 小米
        ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"),
        // 华为
        ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity"),
        ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"),
        // OPPO / OnePlus / realme
        ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"),
        ComponentName("com.coloros.safecenter", "com.coloros.safecenter.startupapp.StartupAppListActivity"),
        ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity"),
        // vivo / iQOO
        ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity"),
        ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"),
        // 荣耀
        ComponentName("com.hihonor.systemmanager", "com.hihonor.systemmanager.startupmgr.ui.StartupNormalAppListActivity"),
        // 魅族
        ComponentName("com.meizu.safe", "com.meizu.safe.security.SHOW_APPSEC"),
    )

    /**
     * 按厂商品牌猜对应的自启动设置页。命中即跳转;全部不命中则 toast 引导用户手动到系统设置开启。
     */
    fun openAutoStartSettings(ctx: Context) {
        for (cn in candidates) {
            val intent = Intent().apply {
                component = cn
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            try {
                ctx.startActivity(intent)
                return
            } catch (_: Exception) {
                // 继续尝试下一个
            }
        }
        Toast.makeText(ctx, R.string.autostart_unknown_vendor, Toast.LENGTH_LONG).show()
    }

    fun isLikelyChineseVendor(): Boolean {
        val brand = Build.BRAND.lowercase()
        return brand in setOf(
            "xiaomi", "redmi", "huawei", "honor", "oppo", "oneplus",
            "realme", "vivo", "iqoo", "meizu",
        )
    }
}
