package chat.vojo.proxy.service

import android.app.PendingIntent
import android.content.Intent
import android.net.VpnService
import android.os.Build
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import chat.vojo.proxy.MainActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

/** Quick Settings tile: one-tap connect/disconnect from the shade. */
class ProxyTileService : TileService() {

    private var scope: CoroutineScope? = null

    override fun onStartListening() {
        scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate).also { sc ->
            sc.launch { VpnState.status.collect { render(it) } }
        }
    }

    override fun onStopListening() {
        scope?.cancel()
        scope = null
    }

    private fun render(status: VpnState.Status) {
        val tile = qsTile ?: return
        tile.state = when (status) {
            VpnState.Status.CONNECTED, VpnState.Status.CONNECTING -> Tile.STATE_ACTIVE
            else -> Tile.STATE_INACTIVE
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            tile.subtitle = when (status) {
                VpnState.Status.CONNECTED -> "online"
                VpnState.Status.CONNECTING -> "connecting"
                VpnState.Status.STOPPING -> "stopping"
                VpnState.Status.ERROR -> "error"
                VpnState.Status.DISCONNECTED -> null
            }
        }
        tile.updateTile()
    }

    override fun onClick() {
        when (VpnState.status.value) {
            VpnState.Status.CONNECTED, VpnState.Status.CONNECTING ->
                ProxyVpnService.stop(this)
            else -> {
                if (VpnService.prepare(this) == null) {
                    ProxyVpnService.start(this)
                } else {
                    // VPN consent needed — open the app to run the system dialog.
                    openApp()
                }
            }
        }
    }

    private fun openApp() {
        val intent = Intent(this, MainActivity::class.java)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            startActivityAndCollapse(
                PendingIntent.getActivity(this, 2, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
            )
        } else {
            @Suppress("DEPRECATION", "StartActivityAndCollapseDeprecated")
            startActivityAndCollapse(intent)
        }
    }
}
