package com.renrenliao.im.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.renrenliao.im.base.BaseViewModel
import com.renrenliao.im.bean.UserInfo
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 kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 **@ClassName GroupMemberViewModel
 **@Description
 **@Author gan
 **@Date 2022/6/10 19:24
 **/
class GroupMemberViewModel(
    private val remoteRepo: RemoteDataSource,
    private val localDataSource: LocalDataSource
) : BaseViewModel() {

    val friendsLiveData = MutableLiveData<List<UserInfo>>()
    val createGroupLiveData = MutableLiveData<Boolean>()

    //获取全部好友
    fun getFriends(){
        viewModelScope.launch {
            val result = withContext(Dispatchers.IO){
                localDataSource.getFriends()
            }
            friendsLiveData.value = result
        }
    }

    //模糊查询
    fun getFriendsByKey(key:String){
        viewModelScope.launch {
            val result = withContext(Dispatchers.IO){
                localDataSource.getFriendsByKey(key)
            }
            friendsLiveData.value = result
        }
    }

    fun createGroup(map: HashMap<String,String>){
        val map = MapUtils.getComParam(map)
        launchUI({
            val result = withContext(Dispatchers.IO){
                remoteRepo.createGroup(map)
            }
            result.checkSuccess {
                withContext(Dispatchers.IO){
                    it.isInGroup = 1
                    it.joinTime = it.createTime
                    it.createUserName = DataCacheUtils.getUserInfo()?.nickname
                    localDataSource.insertGroup(it)
                }
                createGroupLiveData.value = true
            }

        })
    }


}