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 androidx.paging.PagingData
import com.example.pmulabs.room.models.Article
import com.example.pmulabs.room.models.Comment
import com.example.pmulabs.room.models.Tag
import com.example.pmulabs.room.models.User
import com.example.pmulabs.room.repository.ArticleRepository
import com.example.pmulabs.room.repository.CommentRepository
import com.example.pmulabs.room.repository.TagRepository
import com.example.pmulabs.room.repository.UserRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

class ArticlePageScreenViewModel(
    private val tagRepository: TagRepository,
    private val commentRepository: CommentRepository,
    private val articleRepository: ArticleRepository,
    private val userRepository: UserRepository
) : ViewModel() {
    private val articleid = mutableStateOf<Int?>(null)
    private val tagid = mutableStateOf<Int?>(null)
    var article by mutableStateOf<Article?>(null)
    var tag by mutableStateOf<Tag?>(null)
    val comments: Flow<PagingData<Comment>> = commentRepository.getComments()

    fun getArticleById(articleId:Int) {
        articleid.value = articleId
        viewModelScope.launch {
            article = articleRepository.getArticleById(articleid.value!!)
                .filterNotNull()
                .first()
        }
    }

    var tagList by mutableStateOf<List<Tag>>(emptyList())
    fun setTagList() {
        viewModelScope.launch {
            tagList=tagRepository.getAllTags().first()
        }
    }

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

    suspend fun updateUser(user: User) {
        userRepository.updateUser(user)
    }

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

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

    fun getTagById(tagId:Int) {
        tagid.value = tagId
        viewModelScope.launch {
            tag = tagRepository.getTagById(tagid.value!!)
                .filterNotNull()
                .first()
        }
    }
}