package com.jihe.punchnet.data

import android.app.Activity.RESULT_CANCELED
import android.app.Activity.RESULT_OK
import android.app.Application
import android.content.Context
import android.content.Intent
import android.net.VpnService
import android.os.Build
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.core.content.ContextCompat.startForegroundService
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.jihe.punchnet.PunchnetService
import com.jihe.punchnet.PunchnetServiceArgument
import com.jihe.punchnet.RouteInfo
import com.jihe.punchnet.sdlan.utils.ipToString
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.forEach
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch

class ServiceViewModel(application: Application): AndroidViewModel(application) {
    private val _isRunning = mutableStateOf(false)
    val isRunning: State<Boolean> = _isRunning

    fun startService(context: Context, routes: Array<RouteItem>) {
        // should has the permission
        startVpnService(context, routes)
        _isRunning.value = true
    }

    private fun startVpnService(context: Context, routes: Array<RouteItem>) {
        val intent = Intent(context, PunchnetService::class.java)
        intent.putExtra("argument", PunchnetServiceArgument(
            "",
            routes,
        ))

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent)
        } else {
            context.startService(intent)
        }
        Toast.makeText(context, "VPN service started", Toast.LENGTH_SHORT).show()
    }


    fun stopVpnService(context: Context) {
        Log.d("STOP PUNCHNET", "stopping PUNCHNET")
        context.startService(Intent(context, PunchnetService::class.java).also { it.action=
            PunchnetService.ACTION_DISCONNECT })
        // stopService(Intent(this, PunchnetService::class.java))
        Log.d("STOPPED PUNCHNET", "stopping PUNCHNET")
        _isRunning.value = false
        // Toast.makeText(this, "VPN service stopped", Toast.LENGTH_SHORT).show()
    }
}