package com.example.pmulabs.viewModels

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.example.pmulabs.room.models.Comment
import com.example.pmulabs.room.models.User
import com.example.pmulabs.room.repository.CommentRepository
import com.example.pmulabs.room.repository.UserRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class CommentItemViewModel(
    private val userRepository: UserRepository,
    private val commentRepository: CommentRepository
) : ViewModel() {
    suspend fun updateComment(comment: Comment) {
        commentRepository.updateComment(comment)
    }

    var commentList by mutableStateOf<Flow<List<Comment>>>(commentRepository.getAllComments())
    var commListByArticle by mutableStateOf<List<Comment>>(emptyList())
    var userListByArticle by mutableStateOf<List<User>>(emptyList())

    suspend fun getCount(articleId: Int): Int = withContext(Dispatchers.IO) {
        commentRepository.getCountComment(articleId)
    }

    fun getUsersByArticle(articleId: Int) {
        viewModelScope.launch {
            val count=getCount(articleId)
            for(item in commentList.first()){
                if(item.articleId==articleId){
                    commListByArticle+=item
                }
                if(commListByArticle.size>count){
                    commListByArticle -= commListByArticle[commListByArticle.size-1]
                }
            }
            for(item in commListByArticle){
                userListByArticle+=userRepository.getUserById(item.userId).first()
                if(userListByArticle.size>count){
                    userListByArticle -= userListByArticle[userListByArticle.size-1]
                }
            }
        }
    }

    suspend fun deleteComment(comment: Comment) {
        commentRepository.deleteComment(comment)
    }
}