package com.aiosman.ravenow.ui.follower

import android.icu.util.Calendar
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.paging.map
import com.aiosman.ravenow.data.AccountFollow
import com.aiosman.ravenow.data.AccountService
import com.aiosman.ravenow.entity.FollowItemPagingSource
import com.aiosman.ravenow.data.AccountServiceImpl
import com.aiosman.ravenow.data.UserServiceImpl
import com.aiosman.ravenow.data.UserService
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.data.api.UpdateNoticeRequestBody
import com.aiosman.ravenow.event.FollowChangeEvent
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

/**
 * 关注消息列表的 ViewModel
 */
object FollowerNoticeViewModel : ViewModel() {
    private val accountService: AccountService = AccountServiceImpl()
    private val userService: UserService = UserServiceImpl()
    private val _followerItemsFlow =
        MutableStateFlow<PagingData<AccountFollow>>(PagingData.empty())
    val followerItemsFlow = _followerItemsFlow.asStateFlow()
    var isFirstLoad = true

    init {
        EventBus.getDefault().register(this)
    }

    fun reload(force: Boolean = false) {
        if (!isFirstLoad && !force) {
            return
        }
        isFirstLoad = false
        viewModelScope.launch {
            Pager(
                config = PagingConfig(pageSize = 5, enablePlaceholders = false),
                pagingSourceFactory = {
                    FollowItemPagingSource(
                        accountService
                    )
                }
            ).flow.cachedIn(viewModelScope).collectLatest {
                _followerItemsFlow.value = it
            }
        }
    }
    @Subscribe
    fun onFollowChangeEvent(event: FollowChangeEvent) {
        updateIsFollow(event.userId, event.isFollow)
    }
    private fun updateIsFollow(id: Int, isFollow: Boolean = true) {
        val currentPagingData = _followerItemsFlow.value
        val updatedPagingData = currentPagingData.map { follow ->
            if (follow.userId == id) {
                follow.copy(isFollowing = isFollow)
            } else {
                follow
            }
        }
        _followerItemsFlow.value = updatedPagingData
    }
    suspend fun followUser(userId: Int) {
        userService.followUser(userId.toString())
        EventBus.getDefault().post(FollowChangeEvent(userId, true))
    }

    suspend fun updateNotice() {
        var now = Calendar.getInstance().time
        accountService.updateNotice(
            UpdateNoticeRequestBody(
                lastLookFollowTime = ApiClient.formatTime(now)
            )
        )
    }
    fun ResetModel() {
        isFirstLoad = true
    }

    override fun onCleared() {
        super.onCleared()
        EventBus.getDefault().unregister(this)
    }
}