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.OrderRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class OrdersViewModel @Inject constructor(
    private val orderRepository: OrderRepository
) : ViewModel() {
    private val _preparingOrders = MutableLiveData<List<OrderWithProducts>>()
    private val _preparedOrders = MutableLiveData<List<OrderWithProducts>>()
    private val _processedOrders = MutableLiveData<List<OrderWithProducts>>()

    val preparingOrders: LiveData<List<OrderWithProducts>>
        get() = _preparingOrders
    val preparedOrders: LiveData<List<OrderWithProducts>>
        get() = _preparedOrders
    val processedOrders: LiveData<List<OrderWithProducts>>
        get() = _processedOrders

    init {
        viewModelScope.launch {
            orderRepository.getAll().collect { allOrders ->
                _preparingOrders.postValue(allOrders.filter { it.order.status == OrderStatus.Готовится.name })
                _preparedOrders.postValue(allOrders.filter { it.order.status == OrderStatus.Готово.name })
                _processedOrders.postValue(allOrders.filter { it.order.status == OrderStatus.Выдано.name })
            }
        }
    }

    fun changeOrderStatus(order: OrderWithProducts, newStatus: String) {
        val model = order.order
        model.status = newStatus

        viewModelScope.launch{
            orderRepository.update(model)
        }
    }

    fun deleteOrder(order: OrderWithProducts) {
        viewModelScope.launch{
            orderRepository.delete(order.order)
        }
    }


}