package com.example.myapplication.database.room.viewmodel.cart

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.example.myapplication.database.room.model.item.Item
import com.example.myapplication.database.room.model.item.ItemFromCart
import com.example.myapplication.database.room.model.rent.Rent
import com.example.myapplication.database.room.model.rent.RentItemCrossRef
import com.example.myapplication.database.room.model.user.UserItemCrossRef
import com.example.myapplication.database.room.repository.online.RentItemRepository
import com.example.myapplication.database.room.repository.online.RentRepository
import com.example.myapplication.database.room.repository.online.UserItemRepository
import com.example.myapplication.database.room.repository.online.UserRepository

class CartViewModel(
    private val userItemRepository: UserItemRepository,
    private val rentRepository: RentRepository,
    private val rentItemRepository: RentItemRepository,
    private val userRepository: UserRepository,
) : ViewModel() {
    //private val userUid: Int = 1
    var cartUiState by mutableStateOf(CartUiState())
        private set

    suspend fun refreshState(userId: Int) {
        val cart = userRepository.getCartByUser(userId)
        cartUiState = CartUiState(cart)
    }

    suspend fun addToRent(userId: Int, items: List<ItemFromCart>) {
        if (items.isEmpty())
            return
        val rentId = rentRepository.insertRent(Rent(0, userId))
        items.forEach { item ->
            rentItemRepository.insertRentItem(
                RentItemCrossRef(
                    rentId.toInt(),
                    item.uid,
                    item.weight,
                    item.radius,
                    item.colorbike,
                    item.count
                )
            )
        }
        userItemRepository.deleteUserItems(userId)
        refreshState(userId)
    }

    suspend fun removeFromCart(user: Int, item: Item, count: Int = 1) {
        userItemRepository.deleteUserItem(UserItemCrossRef(user, item.uid, count))
        refreshState(user)
    }

    suspend fun updateFromCart(userId: Int, item: Item, count: Int, availableCount: Int)
            : Boolean {
        if (count == 0) {
            removeFromCart(userId, item, count)
            return false
        }
        if (count > availableCount)
            return false
        userItemRepository.updateUserItem(UserItemCrossRef(userId, item.uid, count))
        refreshState(userId)
        return true
    }
}

data class CartUiState(val itemList: List<ItemFromCart> = listOf())