package app.xixi.nomo

import android.app.Application
import android.content.Context
import android.os.Process
import io.flutter.FlutterInjector
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import android.util.Log
class App : Application() {
    
    companion object {
        private const val TAG = "App"
        private const val ENGINE_ID = "main_engine"
        
        // 获取缓存的Flutter引擎
        fun getFlutterEngine(): FlutterEngine? {
            return FlutterEngineCache.getInstance().get(ENGINE_ID)
        }
        
        // 检查是否为主进程
        private fun isMainProcess(context: Context): Boolean {
            val processName = getProcessName(context)
            val packageName = context.packageName
            return processName == packageName
        }
        
        // 获取当前进程名
        private fun getProcessName(context: Context): String {
            val pid = Process.myPid()
            val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
            val runningApps = activityManager.runningAppProcesses
            runningApps?.forEach { processInfo ->
                if (processInfo.pid == pid) {
                    return processInfo.processName
                }
            }
            return context.packageName
        }
    }
    
    override fun onCreate() {
        super.onCreate()
        
        // 检查是否为主进程
        if (isMainProcess(this)) {
            Log.d(TAG, "主进程启动，开始初始化...")
            
            // 在主进程中初始化Flutter引擎
            initializeFlutterEngine()
            
            // 其他应用初始化逻辑
            initializeApp()
        } else {
            Log.d(TAG, "非主进程启动，跳过Flutter引擎初始化")
        }
    }
    
    private fun initializeFlutterEngine() {
        try {
            Log.d(TAG, "开始在主进程中初始化Flutter引擎...")
            
            // 确保Flutter注入器已初始化
            FlutterInjector.instance()
            
            // 创建Flutter引擎
            val flutterEngine = FlutterEngine(this)
            // .apply {
            //     // 设置Dart入口点
            //     dartExecutor.executeDartEntrypoint(
            //         DartExecutor.DartEntrypoint.createDefault()
            //     )
                
            //     // 设置生命周期通道
            //     lifecycleChannel.appIsResumed()
            // }
            
            // 缓存引擎以便后续使用
//            FlutterEngineCache.getInstance().put(ENGINE_ID, flutterEngine)
            
            Log.d(TAG, "Flutter引擎在主进程中初始化完成")
            
        } catch (e: Exception) {
            Log.e(TAG, "Flutter引擎初始化失败: ${e.message}", e)
        }
    }

    private fun initializeApp() {
        try {
            Log.d(TAG, "开始初始化应用...")
            
            // 在这里添加其他应用级别的初始化逻辑
            // 例如：初始化第三方SDK、配置日志等

        } catch (e: Exception) {
            Log.e(TAG, "应用初始化失败: ${e.message}", e)
        }
    }
    
    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        // 确保Flutter注入器已初始化（在所有进程中）
        FlutterInjector.instance()
    }
}
