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.Article
import com.example.pmulabs.room.models.Tag
import com.example.pmulabs.room.repository.ArticleRepository
import com.example.pmulabs.room.repository.CommentRepository
import com.example.pmulabs.room.repository.TagRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ArticleItemViewModel(
    private val tagRepository: TagRepository,
    private val commentRepository: CommentRepository,
    private val articleRepository: ArticleRepository
) : ViewModel() {
    var tagList by mutableStateOf<List<Tag>>(emptyList())
    fun setTagList() {
        viewModelScope.launch {
            tagList=tagRepository.getAllTags().first()
        }
    }

    suspend fun updateArticle(article: Article) {
        articleRepository.updateArticle(article)
    }

    suspend fun deleteArticle(article: Article) {
        articleRepository.deleteArticle(article)
    }

    suspend fun getTagByName(name: String) : Tag {
        return tagRepository.getTagByName(name).first()
    }

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

}