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.PlaymateCommentData
import com.adealink.weparty.playmate.comment.data.PlaymateCommentReq
import com.adealink.weparty.playmate.datasource.remote.PlaymateHttpService
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 commentList = mutableListOf<PlaymateCommentData>()
    val commentListRltLD = MutableLiveData<Rlt<Any>>()
    val commentListLD = MutableLiveData<List<PlaymateCommentData>>()
    private val pageHandler = PageHandler()

    private var playmateID: String? = null
    fun setPlaymate(id: String?) {
        this.playmateID = id
    }

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

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

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

    private suspend fun pullList() {
        val id = playmateID
        if (id.isNullOrEmpty()) {
            commentListRltLD.send(Rlt.Failed(CommonDataNullError()))
            return
        }
        if (pageHandler.isEnd) {
            commentListRltLD.send(Rlt.Failed(NoMoreDataError()))
            return
        }
        val rlt = playmateHttpService.getPlaymateComment(
            PlaymateCommentReq(
                playmateId = id,
                page = PageReq(size = pageHandler.pageSize, next = pageHandler.currentPage)
            )
        )
        when (rlt) {
            is Rlt.Failed -> {
                commentListRltLD.send(rlt)
            }

            is Rlt.Success -> {
                pageHandler.nextPage(rlt.data.data?.next)
                commentList.addAll(rlt.data.data?.list ?: emptyList())
                commentListRltLD.send(rlt)
                commentListLD.send(commentList)
            }
        }
    }


}