package com.example.shawarma.viewmodels

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.shawarma.data.models.ProductModel
import com.example.shawarma.data.repos.ProductRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class ProductViewModel @Inject constructor(
    private val productRepository: ProductRepository
) : ViewModel() {
    private val _addingProductState = MutableLiveData<Boolean>(false)
    val addingProductState: LiveData<Boolean?>
        get() = _addingProductState

    private val _product = MutableLiveData<ProductModel>()
    val product: LiveData<ProductModel>
        get() = _product

    fun addProduct(name: String, price: Int, oldPrice: Int? = null) {
        viewModelScope.launch {
            productRepository.insert(ProductModel(null, name, price, oldPrice))
            _addingProductState.postValue(true)
        }
    }

    fun getProduct(productId: Int) {
        viewModelScope.launch {
            productRepository.getById(productId).collect {
                _product.postValue(it)
            }
        }
    }

    fun updateProduct(name: String, price: Int, oldPrice: Int? = null) {
        viewModelScope.launch {
            productRepository.update(ProductModel(product.value?.id, name, price, oldPrice))
            _addingProductState.postValue(true)
        }
    }
}