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.api.ServerService
import com.example.dtf.dto.Credentials
import com.example.dtf.repositories.offline.OfflineUserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

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

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

    fun register(username: String, password: String, confirmPassword: String) {
        if (username.length < 5 || username.length > 20) {
            _successState.postValue(false)
            return
        }

        if (password.length < 8 || password.length > 30) {
            _successState.postValue(false)
            return
        }

        if (password != confirmPassword) {
            _successState.postValue(false)
            return
        }
        viewModelScope.launch {
            if (serverService.register(Credentials(username, password)) == "NOT OK") {
                _successState.postValue(false)
            } else {
                _successState.postValue(true)
            }
        }
    }
}