package com.example.dtf.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.dtf.PreferencesManager
import com.example.dtf.models.Like
import com.example.dtf.repositories.ICategoryRepository
import com.example.dtf.repositories.ILikeRepository
import com.example.dtf.repositories.IPostRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class PostsViewModel @Inject constructor(
    private val postRepository: IPostRepository,
    private val categoryRepository: ICategoryRepository,
    private val likeRepository: ILikeRepository
) : ViewModel() {
    fun getLikes(postId: Int) = likeRepository.countByPost(postId)

    fun likePost(sharedPref: PreferencesManager, postId: Int) {
        val userId = sharedPref.getData("userId", "-1").toInt()

        if (userId == -1) return

        viewModelScope.launch {
            likeRepository.insert(Like(userId, postId))
        }
    }

    fun unlikePost(sharedPref: PreferencesManager, postId: Int) {
        val userId = sharedPref.getData("userId", "-1").toInt()

        if (userId == -1) return

        viewModelScope.launch {
            likeRepository.delete(Like(userId, postId))
        }
    }

    fun isLiked(sharedPref: PreferencesManager, postId: Int)
            = likeRepository.isLikedByUser(
        sharedPref.getData("userId", "-1").toInt(),
        postId
    )

    fun getCategoriesListUiState() = categoryRepository.getAll()

    fun getInitialCategory() = categoryRepository.getFirst()

    fun getPostsListUiState(categoryId: Int) = postRepository.getByCategory(categoryId)
}