package ru.fincode.tsudesk.feature.news.presentation.screen

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import ru.fincode.tsudesk.feature.news.domain.model.NewsItem
import ru.fincode.tsudesk.feature.news.domain.usecase.GetNewsPagingUseCase
import javax.inject.Inject

@HiltViewModel
class NewsViewModel @Inject constructor(
    private val getNewsPagingUseCase: GetNewsPagingUseCase
) : ViewModel() {

    private val _state = MutableStateFlow(NewsUiState())
    val state: StateFlow<NewsUiState> = _state.asStateFlow()

    val newsPaging: Flow<PagingData<NewsItem>> =
        getNewsPagingUseCase(
            queryFlow = state.map { it.query },
            scope = viewModelScope
        )

    fun onEvent(event: NewsEvent) {
        when (event) {
            is NewsEvent.QueryChanged ->
                _state.update { it.copy(query = event.value) }

            NewsEvent.ClearQuery ->
                _state.update { it.copy(query = "") }
        }
    }
}