package com.renrenliao.im.viewmodel

import androidx.lifecycle.MutableLiveData
import com.renrenliao.im.base.BaseViewModel
import com.renrenliao.im.ext.toast
import com.renrenliao.im.http.checkError
import com.renrenliao.im.http.checkSuccess
import com.renrenliao.im.model.repository.LocalDataSource
import com.renrenliao.im.model.repository.RemoteDataSource
import com.renrenliao.im.utils.DataCacheUtils
import com.renrenliao.im.utils.MapUtils
import com.renrenliao.im.utils.RingToast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 **@ClassName FriendRemarkViewModel
 **@Description
 **@Author gan
 **@Date 2022/6/15 13:13
 **/
class FriendRemarkViewModel(private val localDataSource: LocalDataSource,private val remoteDataSource: RemoteDataSource):BaseViewModel() {

    val remarkLiveData = MutableLiveData<Boolean>()

    fun remark(friendUid:String,buddyRemark:String){
        var map = HashMap<String,String>()
        map["friendUid"] = friendUid
        map["buddyRemark"] = buddyRemark
        map = MapUtils.getComParam(map)

        launchUI({
            val result = withContext(Dispatchers.IO){
                remoteDataSource.friendRemark(map)
            }
            result.checkSuccess {
                val isFriend = withContext(Dispatchers.IO){
                    localDataSource.isFriend(DataCacheUtils.getUid(),friendUid)
                }
                //是好友 更新本地数据库
                if (isFriend){
                    withContext(Dispatchers.IO){
                        localDataSource.updateFriendRemark(DataCacheUtils.getUid(),friendUid,buddyRemark)
                    }
                }

                remarkLiveData.value = true
            }
            result.checkError {
                RingToast.show(it.errorMsg)
            }

        }, isShowDiaLoading = true)
    }
}