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.ICategoryRepository
import com.example.dtf.repositories.IPostRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import java.util.Date
import javax.inject.Inject

@HiltViewModel
class NewPostViewModel @Inject constructor(
    private val postRepository: IPostRepository,
    private val categoryRepository: ICategoryRepository
) : ViewModel() {
    private val _addingPostState = MutableLiveData<Boolean?>(null)
    val addingPostState: LiveData<Boolean?>
        get() = _addingPostState

    fun getCategories() = categoryRepository.getAllCached()

    fun calmAddingState() {
        _addingPostState.value = null
    }

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

        viewModelScope.launch {
            if (title.isNotEmpty() && content.isNotEmpty()) {
                postRepository.insert(
                    Post(
                        null,
                        title,
                        content,
                        "${Date().year + 1900}-${Date().month + 1}-${Date().date}",
                        sharedPref.getData("userId", "0").toInt(),
                        categoryId
                    )
                )

                _addingPostState.postValue(true)
            } else {
                _addingPostState.postValue(false)
            }
        }
    }
}