package com.renrenliao.im.viewmodel

import androidx.lifecycle.MutableLiveData
import com.renrenliao.im.base.BaseViewModel
import com.renrenliao.im.http.checkSuccess
import com.renrenliao.im.im.AlarmEntity
import com.renrenliao.im.im.AlarmHelper
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.StringUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 **@ClassName AddFriendSureViewModel
 **@Description
 **@Author gan
 **@Date 2022/6/21 12:44
 **/
class AddFriendSureViewModel(
    val remoteDataSource: RemoteDataSource,
    val localDataSource: LocalDataSource
) : BaseViewModel() {

    val agreeLiveData = MutableLiveData<Boolean>()

    fun agreeAddFriend(buddyRemark: String, alarmEntity: AlarmEntity) {
        var map = HashMap<String, String>()
        map["desc"] = ""
        map["buddyRemark"] = buddyRemark
        map["friendUid"] = alarmEntity.tid.toString()
        map["userUid"] = DataCacheUtils.getUid()

        map = MapUtils.getComParam(map)

        launchUI({
            val result = withContext(Dispatchers.IO) {
                remoteDataSource.agreeAddFriend(map)
            }
            result.checkSuccess {
                //删除本地好友请求数据和临时聊天数据 //现在没有临时聊天
                //添加好友数据
                //添加是好友的通知
                //更新修改头像
                withContext(Dispatchers.IO){
                    localDataSource.deleteAlarm(DataCacheUtils.getUid(),alarmEntity.gId.toString())
                    localDataSource.insertFriend(it)
                    val singleAlarm = AlarmHelper.createSingleAlarm(it)
                    localDataSource.insertAlarm(singleAlarm)
                    localDataSource.updateAvatarVersion(DataCacheUtils.getUid(),it.userUid,StringUtils.getAvatarVersion(it.userAvatarFileName))
                }

                agreeLiveData.value = true
            }

        },isShowToast = true)
    }
}