package xyz.magicalbits.smsremote.device

import androidx.compose.runtime.Immutable
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import xyz.magicalbits.smsremote.network.NetworkClient

class DeviceViewModel : ViewModel() {
    private var deviceId: String = ""
    private val _deviceData = MutableLiveData<DeviceScreenState>()
    val deviceData: LiveData<DeviceScreenState> = _deviceData

    fun setDeviceData(newDeviceId: String?, name: String?, type: String?) {
        if (newDeviceId != null && name != null) {
            deviceId = newDeviceId

            var simCardDtoList: List<NetworkClient.SimCardDto> = listOf()
            viewModelScope.launch {
                val networkClient = NetworkClient()
                simCardDtoList = networkClient.getSimCardsByAccessKey(deviceId)
                println("sims: $simCardDtoList")
            }.invokeOnCompletion {
                // FIXME waiting for the response causes brief moment of DeviceError() before _deviceData is updated ...
                //  a solution: caching SIM phone numbers of all discovered devices locally on startup and updating them
                //  only on startup (implicit behavior) or with a pull-down refresh action (not done yet)

                // placeholder since there's no API reading logic yet
                _deviceData.value =
                    DeviceScreenState(
                        deviceId = deviceId,
                        name = name,
                        phoneNumbers = simCardDtoList.map { it.phone_number },
                    )
                println("sims live: ${_deviceData.value!!.phoneNumbers}")
            }
        }
    }
}

@Immutable
data class DeviceScreenState(
    val deviceId: String,
    val name: String,
    val phoneNumbers: List<String>
)
