package de.hackernet.wireguardtv.tile

import android.graphics.drawable.Icon
import android.os.Build
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import androidx.annotation.RequiresApi
import de.hackernet.wireguardtv.R
import de.hackernet.wireguardtv.vpn.WireGuardTunnelService

/**
 * Quick Settings Tile für schnelles VPN Toggle
 * Funktioniert auf Fire TV mit Developer Options
 */
@RequiresApi(Build.VERSION_CODES.N)
class VpnTileService : TileService() {

    override fun onStartListening() {
        super.onStartListening()
        updateTileState()
    }

    override fun onClick() {
        super.onClick()
        
        val service = WireGuardTunnelService.getInstance()
        
        if (service?.isConnected() == true) {
            // Disconnect
            service.let {
                kotlinx.coroutines.runBlocking {
                    it.disconnect()
                }
            }
        } else {
            // Für Connect müsste man zur App navigieren
            // da VPN Permission Dialog nicht im Tile-Kontext funktioniert
            val intent = packageManager.getLaunchIntentForPackage(packageName)
            intent?.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivityAndCollapse(intent)
        }
        
        updateTileState()
    }

    private fun updateTileState() {
        val tile = qsTile ?: return
        
        val isConnected = WireGuardTunnelService.getInstance()?.isConnected() == true
        
        tile.state = if (isConnected) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
        tile.label = if (isConnected) "VPN An" else "VPN Aus"
        tile.icon = Icon.createWithResource(
            this,
            if (isConnected) R.drawable.ic_vpn_connected else R.drawable.ic_vpn_disconnected
        )
        
        tile.updateTile()
    }
}
