package com.renrenliao.im.viewmodel

import androidx.lifecycle.viewModelScope
import com.renrenliao.im.base.BaseViewModel
import com.renrenliao.im.http.checkError
import com.renrenliao.im.http.checkSuccess
import com.renrenliao.im.im.AlarmEntity
import com.renrenliao.im.im.AlarmHelper
import com.renrenliao.im.im.AlarmType
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.LogUtils
import com.renrenliao.im.utils.RingToast
import com.renrenliao.im.utils.StringUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

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

    val alarmLiveData = localDataSource.getAlarmListByTypeLiveData(
        DataCacheUtils.getUid(),
        AlarmType.ADDFRIENDREQUEST.value
    )

    fun getAddFriendReq() {
        viewModelScope.launch {
            val result = withContext(Dispatchers.IO) {
                remoteDataSource.getOfflineFriend()
            }
            result.checkSuccess { users ->
                LogUtils.error(users)
                val list = mutableListOf<AlarmEntity>()
                users.map {
                    val alarmEntity = AlarmHelper.createAddFriendAlarm(it)
                    list.add(alarmEntity)
                }
                withContext(Dispatchers.IO) {
                    //更新或插入alarm
                    localDataSource.insertAlarms(list)
                    //更新头像版本
                    users.forEach {
                        localDataSource.updateAvatarVersion(DataCacheUtils.getUid(),it.userUid,StringUtils.getAvatarVersion(it.userAvatarFileName))
                    }
                }

            }
            result.checkError {
                RingToast.show(it.errorMsg)
            }
        }
    }
}