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.OrderStatus
import com.example.shawarma.data.models.OrderWithProducts
import com.example.shawarma.data.repos.OrderProductRepository
import com.example.shawarma.data.repos.OrderRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class CartViewModel @Inject constructor(
    private val orderRepository: OrderRepository,
    private val orderProductRepository: OrderProductRepository
) : ViewModel(){
    private val _unpaidOrder = MutableLiveData<OrderWithProducts>()
    val unpaidOrder: LiveData<OrderWithProducts>
        get() = _unpaidOrder
    private val _paidOrders = MutableLiveData<List<OrderWithProducts>>()
    val paidOrders: LiveData<List<OrderWithProducts>>
        get() = _paidOrders

    fun getOrders(userId: String) {
        if (userId == "null") return
        viewModelScope.launch {
            orderRepository.getUnpaidByUser(userId.toInt()).collect {
                _unpaidOrder.postValue(it)
            }
        }
        viewModelScope.launch {
            orderRepository.getPaidByUser(userId.toInt()).collect {
                _paidOrders.postValue(it)
            }
        }
    }
    fun payForOrder(order: OrderWithProducts) {
        val model = order.order
        model.status = OrderStatus.Готовится.name
        viewModelScope.launch {
            orderRepository.update(model)
        }
    }

    fun removeProductFromOrder(order: OrderWithProducts, productId: Int) {
        val model = order.orderWithProducts[productId].orderProductModel
        if(model.quantity == 1) {
            // delete
            viewModelScope.launch {
                orderProductRepository.delete(model)
            }
        }
        else{
            // update
            model.quantity -= 1
            viewModelScope.launch {
                orderProductRepository.update(model)
            }
        }
    }
    fun addProductToOrder(order: OrderWithProducts, productId: Int) {
        val model = order.orderWithProducts[productId].orderProductModel
        // update
        model.quantity += 1
        viewModelScope.launch {
            orderProductRepository.update(model)
        }

    }
}