package com.example.dtf.viewmodels

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.dtf.PreferencesManager
import com.example.dtf.models.Post
import com.example.dtf.repositories.IPostRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class EditPostViewModel @Inject constructor(
    private val postRepository: IPostRepository
) : ViewModel() {
    private val _editingPostState = MutableLiveData<Boolean?>(null)
    val editingPostState: LiveData<Boolean?>
        get() = _editingPostState

    private val _post = MutableLiveData<Post>()
    val post: LiveData<Post>
        get() = _post

    fun retrievePost(postId: Int) {
        viewModelScope.launch {
            postRepository.getById(postId).collect {
                _post.postValue(it)
            }
        }
    }

    fun calmEditingState() {
        _editingPostState.value = null
    }

    fun editPost(sharedPref: PreferencesManager, postId: Int, title: String, content: String) {
        if (!sharedPref.getData("isModerator", "false").toBooleanStrict()) return

        viewModelScope.launch {
            if (title.isNotEmpty() && content.isNotEmpty()) {
                postRepository.getById(postId).collect {
                    postRepository.update(Post(postId, title, content, it.date, it.user_id, it.category_id))
                    _editingPostState.postValue(true)
                }
            } else {
                _editingPostState.postValue(false)
            }
        }
    }
}