package com.mitchelbv.thuis_c.ui.feyenoord

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mitchelbv.thuis_c.network.feyenoord.FeyenoordRetrofitHelper
import com.mitchelbv.thuis_c.network.feyenoord.FeyenoordService
import com.mitchelbv.thuis_c.network.feyenoord.responses.FeyenoordEventResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

data class FeyenoordUiState(
    val matches: List<Match> = listOf()
)

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

    init {
        fillMatches()
    }

    private fun fillMatches() {
        // TODO Get data from the internet
        val tempMatches = mutableListOf<Match>()
        viewModelScope.launch(Dispatchers.IO) {
            val fApiClient =
                FeyenoordRetrofitHelper.getInstance().create(FeyenoordService::class.java)
            val apiResponse = fApiClient.getEvents()
            for (tabItem in apiResponse.TabItems) {
                val test = arrayOf(tabItem).filter { it.CategoryId == 2 }
                test.forEach {
                    for (item in it.Items)  {
                        tempMatches.add(Match(
                            home_team = item.NameHomeTeam!!,
                            away_team = item.NameAwayTeam!!,
                            date = item.EventStartDateTimeFormatted?.Full!!,
                            begin_time = item.EventStartDateTimeFormatted?.Time!!,
                            end_time = item.EventEndDateTimeFormatted?.Time!!,
                            away_image = item.AwayImageUrl!!,
                            home_image = item.HomeImageUrl!!
                        ))
                    }
                }
            }
            _uiState.value = FeyenoordUiState(matches = tempMatches)
        }
    }
}