package com.renrenliao.im.model.repository

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.room.Query
import com.renrenliao.im.MyApp
//import com.renrenliao.im.bean.AvatarTAG
import com.renrenliao.im.bean.UserInfo
import com.renrenliao.im.db.AppDatabase
import com.renrenliao.im.im.AlarmEntity
import com.renrenliao.im.im.GroupEntity
import com.renrenliao.im.utils.DataCacheUtils
import com.renrenliao.im.utils.LogUtils
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow


/**
 *Author:ganzhe
 *时间:2020/12/28 12:39
 *描述:This is LocalDataSource
 */
class LocalDataSource {


    //创建database
    private val appDatabase = AppDatabase.getInstance(MyApp.CONTEXT)


    companion object {
        //个人信息stateflow  响应一对多
        private val userInfo = UserInfo()//DataCacheUtils.mUserInfo
        private val userFlow = MutableStateFlow(userInfo)
        val readOnlyUserFlow = userFlow.asStateFlow()

        //全局网络状态livedata
        val networkStatusLiveData = MutableLiveData<Int>()

        //全局头像版本liveData
        //val avatarLiveData = AppDatabase.getInstance(MyApp.CONTEXT).avatarTagDao().getAvatarsLiveData(DataCacheUtils.getUid())
    }

    suspend fun updateUserInfo(userInfo: UserInfo) {
        DataCacheUtils.setUserInfo(userInfo)
        userFlow.emit(userInfo)
    }

//    fun getAvatarsLiveData(): LiveData<List<AvatarTAG>> {
//        return appDatabase.avatarTagDao().getAvatarsLiveData(DataCacheUtils.getUid())
//    }

    fun insertFriend(friend: UserInfo) {
        friend.account_uid = DataCacheUtils.getUid()
        appDatabase.friendDao().insertFriend(friend)
    }

    fun insertFriends(friends: List<UserInfo>) {
        friends.forEach {
            it.account_uid = DataCacheUtils.getUid()
        }
        appDatabase.friendDao().insertFriends(friends)
    }


    fun getFriendsLiveData(): Flow<List<UserInfo>> {
        return appDatabase.friendDao().getFriendsLiveData(DataCacheUtils.getUid())
    }

    fun getFriends(): List<UserInfo> {
        return appDatabase.friendDao().getFriends(DataCacheUtils.getUid())
    }

    fun getFriendsByKey(key: String): List<UserInfo> {
        return appDatabase.friendDao().getFriendsByKey(DataCacheUtils.getUid(), key)
    }

    //查询是否是好友
    fun isFriend(account_uid: String, uid: String): Boolean {
        return appDatabase.friendDao().countByUid(account_uid, uid) > 0
    }

    //删除好友
    fun deleteByUid(account_uid: String, uid: String) {
        return appDatabase.friendDao().deleteByUid(account_uid, uid)
    }

    //更新好友备注
    fun updateFriendRemark(account_uid: String, userUid: String, buddyRemark: String) {
        return appDatabase.friendDao().updateFriendRemark(account_uid, userUid, buddyRemark)
    }

    //设置所有好友离线  此方法的应用场景目前是在网络掉线（准确地说是与服务端断开连接）时
    fun setAllFriendsOffline() {
        return appDatabase.friendDao().setAllFriendsOffline(DataCacheUtils.getUid())
    }

    //设置好友状态
    fun setFriendLiveStatus(liveStatus: Int, uid: String) {
        return appDatabase.friendDao().setFriendLiveStatus(liveStatus, uid, DataCacheUtils.getUid())
    }


    fun insertGroup(group: GroupEntity) {
        group.account_uid = DataCacheUtils.getUid()
        appDatabase.groupDao().insertGroup(group)
    }

    fun insertGroups(groups: List<GroupEntity>) {
        groups.forEach {
            it.account_uid = DataCacheUtils.getUid()
        }
        appDatabase.groupDao().insertGroups(groups)
    }


    fun getGroupsLiveData(): Flow<List<GroupEntity>> {
        return appDatabase.groupDao().getGroupsLiveData(DataCacheUtils.getUid())
    }

    //============================== msgDao============================
    //更新消息发送状态
    fun updateSendStatus(sendStatus: Int, fp: String) {
        return appDatabase.msgDao().updateSendStatus(sendStatus, fp, DataCacheUtils.getUid())
    }

    //====================================alarmDao=================================
    //统计全局未读数
    fun countUnRead(): LiveData<Int> {
        return appDatabase.alarmDao().countUnRead(DataCacheUtils.getUid())
    }

    //删除 alarm 不是当前userId的
    fun deleteAlarmNotCurrentUid() {
        return appDatabase.alarmDao().deleteAlarmsNotCurrentUid(DataCacheUtils.getUid())
    }

    //插入alarm
    fun insertAlarm(alarmEntity: AlarmEntity) {
        return appDatabase.alarmDao().insertAlarm(alarmEntity)
    }

    //插入alarms
    fun insertAlarms(alarms: List<AlarmEntity>) {
        return appDatabase.alarmDao().insertAlarms(alarms)
    }

    //查询所有alarm的livedata
    fun getAlarmsLiveData(): LiveData<List<AlarmEntity>> {
        return appDatabase.alarmDao().getAlarmsLiveData(DataCacheUtils.getUid())
    }

    //查询所有alarm的list
    fun getAlarms(): List<AlarmEntity> {
        return appDatabase.alarmDao().getAlarms(DataCacheUtils.getUid())
    }

    //查询alarm
    fun getAlarm(gId: String, msgType: Int): AlarmEntity {
        return appDatabase.alarmDao().getAlarm(DataCacheUtils.getUid(), gId, msgType)
    }

    //删除alarm
    fun deleteAlarm(account_uid: String, gId: String, msgType: Int) {
        appDatabase.alarmDao().deleteAlarm(account_uid, gId, msgType)
    }

    fun deleteAlarm(account_uid: String, gId: String) {
        appDatabase.alarmDao().deleteAlarm(account_uid, gId)
    }

    //查询AlarmLiveData
    fun getAlarmListByTypeLiveData(account_uid: String, msgType: Int): LiveData<List<AlarmEntity>> {
        return appDatabase.alarmDao().getAlarmListByTypeLiveData(account_uid, msgType)
    }
    //更新置顶状态
    fun updateIsTop(account_uid: String,uid: String,msgType:Int,top:Boolean){
        appDatabase.alarmDao().updateIsTop(account_uid, uid, msgType, top)
    }

    //更新已读未读状态
    fun updateReadStatus(account_uid: String,uid: String,msgType:Int,num:Int){
        appDatabase.alarmDao().updateReadStatus(account_uid,uid,msgType,num)
    }

    //=====================================头像============================================

    //更新avatarVersion  先查询  没有 不管  有 判断version 是否相等 不相等 更新 相等不更新
    fun updateAvatarVersion(account_uid: String,uid: String,newVersion:Long) {
        val alarms = appDatabase.alarmDao().getAlarms(account_uid= DataCacheUtils.getUid(), tid= uid)
        if (alarms !=null){
            alarms.forEach {
                if (it.avatarVersion != newVersion){
                    appDatabase.alarmDao().updateAvatarVersion(account_uid,uid,newVersion)
                }
            }
        }
        val friend = appDatabase.friendDao().getFriend(account_uid= DataCacheUtils.getUid(),uid= uid)
        if (friend !=null){
            if (friend.avatarVersion != newVersion){
                appDatabase.friendDao().updateAvatarVersion(account_uid,uid,newVersion)
            }
        }

    }

}