package com.example.shawarma.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import com.example.shawarma.data.models.OrderModel
import com.example.shawarma.data.models.OrderProductModel
import com.example.shawarma.data.models.OrderStatus
import com.example.shawarma.data.models.ProductModel
import com.example.shawarma.data.repos.OrderProductRepository
import com.example.shawarma.data.repos.OrderRepository
import com.example.shawarma.data.repos.ProductRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import java.util.Calendar
import java.util.Date
import javax.inject.Inject

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val productRepository: ProductRepository,
    private val orderRepository: OrderRepository,
    private val orderProductRepository: OrderProductRepository
) : ViewModel() {

    val productListUiState: Flow<PagingData<ProductModel>> = productRepository.getAllProductsPaged()

    val discountListUiState: Flow<PagingData<ProductModel>> = productRepository.getAllDiscountsPaged()


    fun addProductToCart(productId: Int, userId: String) {
        if (userId == "null") return

        viewModelScope.launch {
            val product = productRepository.getById(productId).first()
            val order = orderRepository.getUnpaidByUser(userId.toInt()).first()
            if (order == null) {
                val calendar: Calendar = Calendar.getInstance()
                calendar.time = Date()
                calendar.add(Calendar.HOUR_OF_DAY, 4)
                val newOrderId = orderRepository.insert(OrderModel(null, OrderStatus.Неоплачено.name, userId.toInt(),calendar.time))
                orderProductRepository.insert(OrderProductModel(newOrderId.toInt(), productId, 1, product.price))
            }
            else {
                var isAlreadyAdded = false
                for (prod in order.orderWithProducts) {
                    if (prod.product.id == productId) {
                        val model = prod.orderProductModel
                        model.quantity += 1
                        model.totalPrice += prod.product.price
                        orderProductRepository.update(model)
                        isAlreadyAdded = true
                    }
                }
                if (!isAlreadyAdded) {
                    orderProductRepository.insert(OrderProductModel(order.order.id!!, productId, 1, product.price))
                }
            }
        }
    }
}