package com.example.what_the_fantasy.ui.viewModels

import android.util.Log
import androidx.lifecycle.ViewModel
import com.example.what_the_fantasy.data.model.SrcLanguage
import com.example.what_the_fantasy.data.services.ServicesStub
import com.example.what_the_fantasy.ui.states.CurrentUserState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

class CurrentUserViewModel : ViewModel(){
    private val services = ServicesStub() // faire repository qui gère les services Stub et API
    private val _currentUserState = MutableStateFlow(CurrentUserState())
    var currentUserState : StateFlow<CurrentUserState> = _currentUserState.asStateFlow()


    fun initialiseCurrentUser(index : Int){
        services.getUserById(index)?.let {
                setId(it.id)
                setUsername(it.username)
                setEmail(it.email)
                setPassword(it.password)
                setLangue(it.langage)
                setImage(it.imgUrl)
            }

    }

    fun clearCurrentUser(){
        _currentUserState.value = CurrentUserState()
    }

    fun setId(id : Int){
        _currentUserState.update {it.copy(id = id)}
    }

    fun setUsername(username : String){
        _currentUserState.update {it.copy(username = username)}
    }

    fun setEmail(email : String){
        _currentUserState.update {it.copy(email = email)}
    }

    fun setPassword(password : String){
        _currentUserState.update {it.copy(password = password)}
    }

    fun setConfirmPassword(password : String){
        _currentUserState.update {it.copy(confirmPassword = password)}
    }

    fun setLangue(langue : SrcLanguage){
        _currentUserState.update {it.copy(langage = langue)}
    }
    fun setImage(imagePath : String){
        _currentUserState.update {it.copy(imagePath = imagePath)}
    }




    fun editUsername(username : String, index : Int) : Boolean{
        _currentUserState.update {it.copy(username = username)}
        return services.EditUsername(username, index)
    }

    fun editEmail(email : String, index : Int) : Boolean{
        _currentUserState.update {
            it.copy(email = email)
        }
        return services.EditEmail(email, index)
    }

    fun editPassword(password : String, index : Int){
        services.EditPasswd(password, index)

    }

    fun editLangue(index : Int){
        val langage = services.ChangeLangage(index)

        _currentUserState.update {
            it.copy(langage = langage)
        }
    }
}