package de.hackernet.wireguardtv.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import de.hackernet.wireguardtv.data.SettingsRepository
import de.hackernet.wireguardtv.data.TunnelRepository
import de.hackernet.wireguardtv.vpn.WireGuardTunnelService
import de.hackernet.wireguardtv.web.WebServerService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

/**
 * Boot Receiver für Auto-Connect und WebServer-Autostart Funktionalität
 */
class BootReceiver : BroadcastReceiver() {

    companion object {
        private const val TAG = "BootReceiver"
    }

    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action != Intent.ACTION_BOOT_COMPLETED) return

        Log.i(TAG, "Boot completed, checking autostart settings...")
        val pendingResult = goAsync()

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val settingsRepository = SettingsRepository.getInstance(context)
                val settings = settingsRepository.settingsFlow.first()

                // WebServer Autostart
                if (settings.webServerAutoStart) {
                    Log.i(TAG, "Starting WebServer (autostart enabled)")
                    val webServerIntent = Intent(context, WebServerService::class.java).apply {
                        action = WebServerService.ACTION_START
                    }
                    context.startForegroundService(webServerIntent)
                }

                // VPN Autoconnect
                if (settings.autoConnectOnBoot) {
                    Log.i(TAG, "Auto-connecting VPN (autoconnect enabled), defaultTunnelId=${settings.defaultTunnelId}")
                    val tunnelRepository = TunnelRepository.getInstance(context)

                    // Standard-Tunnel verwenden (nur wenn explizit gesetzt)
                    val tunnelId = settings.defaultTunnelId

                    if (tunnelId != null) {
                        // Prüfen ob der Tunnel existiert
                        val tunnel = tunnelRepository.getTunnel(tunnelId)
                        if (tunnel != null) {
                            Log.i(TAG, "Connecting tunnel: $tunnelId (${tunnel.name})")
                            val serviceIntent = Intent(context, WireGuardTunnelService::class.java).apply {
                                action = WireGuardTunnelService.ACTION_CONNECT
                                putExtra(WireGuardTunnelService.EXTRA_TUNNEL_ID, tunnelId)
                            }
                            context.startForegroundService(serviceIntent)
                        } else {
                            Log.w(TAG, "Tunnel $tunnelId not found in repository")
                        }
                    } else {
                        Log.w(TAG, "No default tunnel configured for autoconnect")
                    }
                } else {
                    Log.i(TAG, "VPN autoconnect disabled (autoConnectOnBoot=${settings.autoConnectOnBoot})")
                }
            } catch (e: Exception) {
                Log.e(TAG, "Error in boot receiver: ${e.message}", e)
            } finally {
                pendingResult.finish()
            }
        }
    }
}
