package ru.myitschool.work.ui.result

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Response
import ru.myitschool.work.api.scan.ApiServiceScan
import ru.myitschool.work.api.scan.CodeJson
import javax.inject.Inject

@HiltViewModel
class ResultViewModel @Inject constructor(
    private val apiService: ApiServiceScan
) : ViewModel() {

    private val _state = MutableStateFlow<ResultState>(ResultState.Initial)
    val state = _state.asStateFlow()

    fun open(login: String, data: CodeJson) {
        viewModelScope.launch {
            _state.value = ResultState.Loading

            apiService.open(login, data).enqueue(object : retrofit2.Callback<Void> {
                override fun onResponse(call: Call<Void>, response: Response<Void>) {
                    Log.d("Open", "Response code: ${response.code()}")

                    when (response.code()) {
                        200 -> {
                            _state.value = ResultState.Success
                        }
                        500 -> {
                            _state.value = ResultState.InvalidCredentials
                        }
                        401 -> {
                            _state.value = ResultState.Error
                        }
                        else -> {
                            _state.value = ResultState.InvalidCredentials
                        }
                    }
                }

                override fun onFailure(call: Call<Void>, t: Throwable) {
                    _state.value = ResultState.Error
                }
            })
        }
    }


    sealed class ResultState {
        data object Initial : ResultState()
        data object InvalidCredentials : ResultState()
        data object Loading : ResultState()
        data object Success : ResultState()
        data object Error : ResultState()
    }
}