package com.craigvg.lichun_android import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import com.craigvg.lichun_android.managers.BillingManager import com.craigvg.lichun_android.navigation.DeepLinkManager import com.craigvg.lichun_android.navigation.DeepLinkRoute import com.craigvg.lichun_android.network.WebSocketManager import com.craigvg.lichun_android.ui.navigation.MainNavigation import com.craigvg.lichun_android.ui.theme.AppColors import com.craigvg.lichun_android.ui.theme.BaoLifeTheme import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.MutableSharedFlow import javax.inject.Inject @AndroidEntryPoint class MainActivity : ComponentActivity() { @Inject lateinit var webSocketManager: WebSocketManager @Inject lateinit var billingManager: BillingManager private var savedGameSpeed: Int? = null private val deepLinkEvents = MutableSharedFlow(extraBufferCapacity = 8) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val initialDeepLinkRoute = DeepLinkManager.parse(intent) applyE2EConfig(initialDeepLinkRoute) enableEdgeToEdge() setContent { BaoLifeTheme { Surface( modifier = Modifier.fillMaxSize(), color = AppColors.background ) { MainNavigation( billingManager = billingManager, initialDeepLinkRoute = initialDeepLinkRoute, deepLinkEvents = deepLinkEvents ) } } } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) DeepLinkManager.parse(intent)?.let { route -> applyE2EConfig(route) deepLinkEvents.tryEmit(route) } } override fun onPause() { super.onPause() val currentSpeed = webSocketManager.player.value.gameSpeed if (currentSpeed > 0) { savedGameSpeed = currentSpeed webSocketManager.setSpeed(0) } } override fun onResume() { super.onResume() if (!webSocketManager.isConnected.value) { webSocketManager.connect() } savedGameSpeed?.let { speed -> webSocketManager.setSpeed(speed) savedGameSpeed = null } } override fun onDestroy() { super.onDestroy() if (isFinishing) { billingManager.endConnection() webSocketManager.disconnect() } } private fun applyE2EConfig(route: DeepLinkRoute?) { val config = route as? DeepLinkRoute.DebugConfig ?: return val wsUrl = config.wsUrl?.takeIf { it.isNotBlank() } ?: return getSharedPreferences("baolife_e2e", MODE_PRIVATE) .edit() .putString("ws_url", wsUrl) .apply() } }