package com.example.dtf.viewmodels

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.dtf.PreferencesManager
import com.example.dtf.api.ServerService
import com.example.dtf.dto.Credentials
import com.example.dtf.repositories.IUserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val serverService: ServerService,
) : ViewModel() {
    private val _successState = MutableLiveData<Boolean?>()
    val successState: LiveData<Boolean?>
        get() = _successState

    fun calmSuccessState() {
        _successState.postValue(null)
    }

    fun login(sharedPref: PreferencesManager, username: String, password: String) {
        viewModelScope.launch {
            val token = serverService.login(Credentials(username, password))

            if (token.token.isEmpty()) {
                _successState.postValue(false)
                return@launch
            }

            ServerService.setToken(token.token)

            val user = serverService.getCurrentUser()

            sharedPref.saveData("token", token.token)
            sharedPref.saveData("username", user.username)
            sharedPref.saveData("isModerator", user.is_moderator.toString())
            sharedPref.saveData("userId", user.id.toString())

            _successState.postValue(true)
        }
    }
}