package com.example.myapplication.database.room.viewmodel.user

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.myapplication.database.room.model.user.User
import com.example.myapplication.database.room.repository.online.UserRepository
import com.example.myapplication.database.room.viewmodel.LoadingViewModel
import kotlinx.coroutines.launch

class RegisterUserViewModel(private val userRepository: UserRepository) : LoadingViewModel() {

    private val _users = MutableLiveData<List<User>>()
    val users: LiveData<List<User>> get() = _users

    fun setUserList() {
        viewModelScope.launch {
            _users.value = userRepository.getAllUsers()
        }
    }

    suspend fun insertUser(user: User) {
        userRepository.insertUser(user)
    }

    suspend fun registerUser(username: String, password: String): Boolean {
        if (password.isNotEmpty() && username.isNotEmpty()) {
            val existingUser = _users.value?.find { it.login == username }
            if (existingUser == null) {
                val newUser = User(null, username,"user" ,password)
                insertUser(newUser)
                setUserList()
                return true
            }
        }
        return false
    }
}