package com.remax.visualnovel.app.viewmodel.base


import com.remax.visualnovel.R
import com.remax.visualnovel.app.base.app.CommonApplicationProxy
import com.remax.visualnovel.entity.response.User
import com.remax.visualnovel.entity.response.base.ApiFailedResponse
import com.remax.visualnovel.entity.response.base.ApiSuccessResponse
import com.remax.visualnovel.entity.response.base.Response
import com.remax.visualnovel.repository.api.LoginRepository
import com.remax.visualnovel.repository.api.UserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject

/**
 * Created by HJW on 2022/10/28
 *
 * User相关viewmodel的父类
 */
@HiltViewModel
open class UserViewModel @Inject constructor() : BaseViewModel() {

    @Inject
    lateinit var userRepository: UserRepository

    private val _userInfoFlow = MutableStateFlow<Response<User>>(Response())
    val userInfoFlow: StateFlow<Response<User>> = _userInfoFlow.asStateFlow()

    suspend fun getMyBaseInfo(): Response<User> {
        return userRepository.getMyBaseInfo().also { _userInfoFlow.value = it }
    }

    /**
     * 公共返回，很多接口操作后需要再次请求用户数据
     */
    protected suspend fun returnUserResponse(response: Response<*>): Response<User> {
        return if (response.isApiSuccess) {
            getMyBaseInfo()
        } else {
            ApiFailedResponse(response.errorCode, response.errorMsg)
        }
    }

    //suspend fun getNimInfo()  = userRepository.getNimInfo()

    @Inject
    lateinit var loginRepository: LoginRepository

    /**
     * 公共返回，检查nickname是否存在
     */
    suspend fun <T> checkNickname(
        nickName: String?,
        exUserId: String? = null,
        apiCall: (suspend () -> Response<T>)? = null
    ): Response<T> {
        val checkRes = loginRepository.checkUserNickname(nickName, exUserId)
        return if (checkRes.isApiSuccess) {
            if (checkRes.data == true) {
                ApiFailedResponse("", CommonApplicationProxy.application.getString(R.string.nickname_exist_error))
            } else {
                apiCall?.invoke() ?: ApiSuccessResponse()
            }
        } else {
            ApiFailedResponse(checkRes.errorCode, checkRes.errorMsg)
        }
    }

}