package com.adealink.weparty.profile.relation.viewmodel

import androidx.lifecycle.MutableLiveData
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.livedata.ExtLiveData
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.profile.datasource.remote.FollowHttpService
import com.adealink.weparty.profile.relation.data.VisitorItemData
import com.adealink.weparty.profile.relation.data.VisitorListReq
import com.adealink.weparty.util.PageHandler
import kotlinx.coroutines.launch

class VisitorViewModel : BaseViewModel() {

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

    val visitorCountLD: ExtLiveData<Long> = ExtMutableLiveData()

    fun getVisitorCount() {
        viewModelScope.launch {
            val rlt = followHttpService.pullVisitorList(VisitorListReq(1, null))
            when (rlt) {
                is Rlt.Failed -> {
                    visitorCountLD.send(0)
                }

                is Rlt.Success -> {
                    visitorCountLD.send(rlt.data.data?.total ?: 0)
                }
            }
        }
    }


    private val visitorList = mutableListOf<VisitorItemData>()
    private val visitorUids = mutableSetOf<String>()
    private val visitorPageHandler = PageHandler()

    val visitorListRltLD = ExtMutableLiveData<Rlt<Any>>()
    val visitorListLD = MutableLiveData<List<VisitorItemData>>()
    fun pullVisitorList() {
        visitorList.clear()
        visitorUids.clear()
        visitorPageHandler.reset()
        loadMoreVisitorList()
    }

    fun hasMoreData(): Boolean {
        return !visitorPageHandler.isEnd
    }

    fun loadMoreVisitorList() {
        viewModelScope.launch {
            val rlt = followHttpService.pullVisitorList(
                VisitorListReq(
                    size = visitorPageHandler.pageSize,
                    next = visitorPageHandler.currentPage
                )
            )
            when (rlt) {
                is Rlt.Failed -> {
                    visitorListRltLD.send(rlt)
                }

                is Rlt.Success -> {
                    visitorPageHandler.nextPage(rlt.data.data?.next)
                    rlt.data.data?.list?.forEach {
                        ProfileModule.updateUserOnline(it.uid, it.online)
                        if (!visitorUids.contains(it.uid)) {
                            visitorList.add(VisitorItemData(it))
                            visitorUids.add(it.uid)
                        }
                    }
                    visitorCountLD.send(rlt.data.data?.total ?: 0)
                    visitorListRltLD.send(rlt)
                    visitorListLD.send(visitorList)
                }
            }
        }
    }


}