package com.aiosman.ravenow.ui.index.tabs.profile.composable

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.entity.AgentEntity
import com.aiosman.ravenow.entity.AgentLoader
import com.aiosman.ravenow.entity.AgentLoaderExtraArgs
import kotlinx.coroutines.launch

class UserAgentsViewModel : ViewModel() {
    private val agentLoader = AgentLoader().apply {
        onListChanged = {
            agents = it
        }
    }
    
    var agents by mutableStateOf<List<AgentEntity>>(emptyList())
        private set
    
    var isLoading by mutableStateOf(false)
        private set
    
    var error by mutableStateOf<String?>(null)
        private set
    
    fun loadUserAgents(userId: Int?) {
        viewModelScope.launch {
            // 先清理之前的数据
            clearAgents()
            isLoading = true
            error = null
            
            try {
                agentLoader.loadData(AgentLoaderExtraArgs(authorId = userId))
            } catch (e: Exception) {
                error = e.message ?: "加载失败"
                e.printStackTrace()
            } finally {
                isLoading = false
            }
        }
    }
    
    fun clearAgents() {
        agents = emptyList()
        error = null
        agentLoader.clear()
    }
}
