package com.adealink.weparty.order.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.frame.network.data.PageReq
import com.adealink.weparty.App
import com.adealink.weparty.order.data.PlaymateOrderListItemData
import com.adealink.weparty.order.data.PlaymateOrderListReq
import com.adealink.weparty.order.datasource.remote.OrderHttpService
import com.adealink.weparty.util.PageHandler
import kotlinx.coroutines.launch

class PlaymateOrderViewModel : BaseViewModel() {
    private val orderHttpService by lazy {
        App.instance.networkService.getHttpService(OrderHttpService::class.java)
    }
    private val orderList = mutableListOf<PlaymateOrderListItemData>()
    private val orderIds = mutableSetOf<String>()
    private val pageHandler = PageHandler()

    val orderListRltLD = ExtMutableLiveData<Rlt<Any>>()
    val orderListLD = MutableLiveData<List<PlaymateOrderListItemData>>()
    fun pullOrderList() {
        orderList.clear()
        orderIds.clear()
        pageHandler.reset()
        loadMoreOrderList()
    }

    fun loadMoreOrderList() {
        viewModelScope.launch {
            val rlt = orderHttpService.pullPlaymateOrderList(
                PlaymateOrderListReq(
                    page = PageReq(size = pageHandler.pageSize, next = pageHandler.currentPage)
                )
            )
            when (rlt) {
                is Rlt.Failed -> {
                    orderListRltLD.send(rlt)
                }

                is Rlt.Success -> {
                    pageHandler.nextPage(rlt.data.data?.next)
                    rlt.data.data?.list?.forEach {
                        if (!orderIds.contains(it.orderId)) {
                            orderList.add(PlaymateOrderListItemData(it))
                            orderIds.add(it.orderId)
                        }
                    }
                    orderListRltLD.send(rlt)
                    orderListLD.send(orderList)
                }
            }
        }
    }

}