package com.adealink.weparty.playmate.userpush.viewmodel

import androidx.lifecycle.MutableLiveData
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.livedata.ExtMutableLiveData
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.App
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.playmate.datasource.remote.PlaymateHttpService
import com.adealink.weparty.playmate.userpush.data.UserPushItemData
import kotlinx.coroutines.launch

class UserPushViewModel : BaseViewModel() {

    private val userPushHttpService by lazy {
        App.instance.networkService.getHttpService(PlaymateHttpService::class.java)
    }

    private val userPushItemList = mutableListOf<UserPushItemData>()
    private val userPushUids = mutableSetOf<String>()
    val userPushListRltLD = ExtMutableLiveData<Rlt<Any>>()
    val userPushListLD = MutableLiveData<List<UserPushItemData>>()
    fun pullUserPushList() {
        userPushItemList.clear()
        userPushUids.clear()
        loadMoreUserList()
    }

    fun loadMoreUserList() {
        viewModelScope.launch {
            val rlt = userPushHttpService.getUserPushList()
            when (rlt) {
                is Rlt.Failed -> {
                    userPushListRltLD.send(rlt)
                }

                is Rlt.Success -> {
                    rlt.data.data?.list?.forEach {
                        ProfileModule.updateUserOnline(it.uid, it.online)
                        if (!userPushUids.contains(it.uid)) {
                            userPushItemList.add(UserPushItemData(it))
                            userPushUids.add(it.uid)
                        }
                    }
                    userPushListRltLD.send(rlt)
                    userPushListLD.send(userPushItemList)
                }
            }
        }
    }


    fun notifyContactedChanged(uid: String, notifyItemChanged: (position: Int) -> Unit) {
        viewModelScope.launch {
            userPushItemList.indexOfFirst { it.data.uid == uid }.let { index ->
                if (index >= 0) {
                    val item = userPushItemList.getOrNull(index) ?: return@launch
                    if (item.data.contacted) {
                        return@launch
                    }
                    item.data.contacted = true
                    notifyItemChanged.invoke(index)
                }
            }
        }
    }

}