package com.adealink.weparty.playmate.comment.viewmodel

import androidx.lifecycle.MutableLiveData
import com.adealink.frame.base.CommonDataNullError
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.frame.network.data.PageReq
import com.adealink.weparty.App
import com.adealink.weparty.network.data.NoMoreDataError
import com.adealink.weparty.playmate.comment.data.PlaymateCommentReq
import com.adealink.weparty.playmate.data.PlaymateCommentData
import com.adealink.weparty.playmate.datasource.remote.PlaymateHttpService
import com.adealink.weparty.playmate.detail.data.BasePlaymateDetailItem
import com.adealink.weparty.playmate.detail.data.PlaymateCommentLabel
import com.adealink.weparty.util.PageHandler
import kotlinx.coroutines.launch

class CommentViewModel : BaseViewModel() {


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

    val labelList = mutableListOf<PlaymateCommentLabel>()
    val commentList = mutableListOf<PlaymateCommentData>()
    val commentListLD = MutableLiveData<Rlt<List<BasePlaymateDetailItem>>>()
    private val pageHandler = PageHandler()

    private var uid: String? = null
    private var categoryCode: String? = null

    fun setPlaymate(uid: String?, categoryCode: String) {
        this.uid = uid
        this.categoryCode = categoryCode
    }

    fun refreshList() {
        viewModelScope.launch {
            pageHandler.reset()
            commentList.clear()
            pullList()
        }
    }

    fun loadMoreList() {
        viewModelScope.launch {
            pullList()
        }
    }

    private suspend fun pullList() {
        val uid = uid
        if (uid.isNullOrEmpty()) {
            commentListLD.send(Rlt.Failed(CommonDataNullError()))
            return
        }
        val categoryCode = categoryCode
        if (categoryCode.isNullOrEmpty()) {
            commentListLD.send(Rlt.Failed(CommonDataNullError()))
            return
        }
        if (pageHandler.isEnd) {
            commentListLD.send(Rlt.Failed(NoMoreDataError()))
            return
        }
        val rlt = playmateHttpService.getPlaymateComment(
            PlaymateCommentReq(
                uid = uid,
                categoryId = categoryCode,
                page = PageReq(size = pageHandler.pageSize, next = pageHandler.currentPage)
            )
        )
        when (rlt) {
            is Rlt.Failed -> {
//                listRltLD.send(rlt)
            }

            is Rlt.Success -> {
//                pageHandler.nextPage(rlt.data.data?.next)
//                playmateList.addAll(rlt.data.data?.list ?: emptyList())
//                listRltLD.send(rlt)
//                listLD.send(playmateList)
            }
        }
    }


}