package com.mitchelbv.thuis_c.ui.card

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mitchelbv.thuis_c.network.card.CardRetrofitHelper
import com.mitchelbv.thuis_c.network.card.CardService
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class CardUiState(
    val cards: List<Card> = listOf()
)

class CardViewModel : ViewModel() {
    private val _uiState = MutableStateFlow(CardUiState())
    val uiState: StateFlow<CardUiState> = _uiState.asStateFlow()

    init {
        fillCards()
    }

    private fun fillCards() {
        val tempCards = mutableListOf<Card>()
        viewModelScope.launch {
            val cApiClient = CardRetrofitHelper.getInstance().create(CardService::class.java)
            val apiResponse = cApiClient.getCards()
            for (card in apiResponse.cards)   {
                tempCards.add(Card(
                    id = card.id!!,
                    code = card.code!!,
                    issuer = card.issuer!!
                ))
            }
        }
        _uiState.value = CardUiState(tempCards)
    }
}