package com.example.myapplication.viewModels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.CreationExtras
import com.example.myapplication.GlobalUser
import com.example.myapplication.MyApp
import com.example.myapplication.api.MyServerService
import com.example.myapplication.api.repository.UserRestRepository
import com.example.myapplication.database.entities.User
import com.example.myapplication.database.entities.UserProductCart
import com.example.myapplication.database.entities.UserWithCartProduct
import com.example.myapplication.database.repository.OfflineUserRepository
import com.example.myapplication.database.repository.UserRepository
import kotlinx.coroutines.flow.Flow

class UserViewModel(
    private val userRepository: UserRepository
) : ViewModel() {
    companion object {
        val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory{
            override fun <T: ViewModel> create(
                modelClass: Class<T>,
                extras: CreationExtras
            ) : T {
                return UserViewModel(UserRestRepository(MyServerService.getInstance())) as T
            }
        }
    }

    fun getUserId(): Int {
        return GlobalUser.getInstance().userId
    }

    fun setUserId(id: Int) {
        GlobalUser.getInstance().userId = id
    }

    suspend fun getAll(): List<User> {
        return userRepository.getAll()
    }
    suspend fun getById(id: Int): User {
        return userRepository.getById(id)
    }
    suspend fun getByAuth(login: String, password: String): User? {
        return userRepository.getByAuth(login, password)
    }


    suspend fun deleteCartProduct(userId: Int, productId: Int) {
        userRepository.deleteCartProduct(userId, productId)
    }

    suspend fun getUserProductsCartById(id: Int): UserWithCartProduct {
        return userRepository.getUserProductCartById(id)
    }

    suspend fun insert(user: User) {
        userRepository.insert(user)
    }
    suspend fun addProductCart(userProduct: UserProductCart) {
        userRepository.addProductCart(userProduct)
    }

}