package com.adealink.weparty.profile.search.viewmodel

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.network.data.NoMoreDataError
import com.adealink.weparty.profile.datasource.remote.SearchHttpService
import com.adealink.weparty.profile.search.data.SearchReq
import com.adealink.weparty.profile.search.data.SearchResultItemData
import com.adealink.weparty.util.PageHandler
import kotlinx.coroutines.launch

class SearchViewModel : BaseViewModel() {

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

    val searchResultLD = ExtMutableLiveData<List<SearchResultItemData>>()
    val searchRltLD = ExtMutableLiveData<Rlt<Any>>()
    private val searchResultList = mutableListOf<SearchResultItemData>()
    private val pageHandler = PageHandler()
    private var keyword: String? = null

    fun search(keyword: String) {
        pageHandler.reset()
        this.keyword = keyword
        searchMore()
    }

    fun searchMore() {
        if (pageHandler.isEnd) {
            searchRltLD.send(Rlt.Failed(NoMoreDataError()))
            return
        }
        viewModelScope.launch {
            val keyword = this@SearchViewModel.keyword ?: return@launch
            val rlt = searchHttpService.search(
                SearchReq(
                    keyword = keyword,
                    page = PageReq(size = pageHandler.pageSize, next = pageHandler.currentPage)
                )
            )
            when (rlt) {
                is Rlt.Failed -> {
                    searchRltLD.send(rlt)
                }

                is Rlt.Success -> {
                    pageHandler.nextPage(rlt.data.data?.next)
                    searchResultList.addAll(rlt.data.data?.list?.map {
                        SearchResultItemData(it)
                    } ?: emptyList())
                    searchRltLD.send(rlt)
                    searchResultLD.send(searchResultList)
                }
            }
        }
    }

    fun notifyFollowChanged(uid: String, follow: Boolean) {
        viewModelScope.launch {
            searchResultList.find { it.data.uid == uid }?.data?.follow = follow
            searchResultLD.send(searchResultList)
        }
    }
}