package com.example.myapplication.viewModels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.CreationExtras
import com.example.myapplication.MyApp
import com.example.myapplication.api.MyServerService
import com.example.myapplication.api.repository.RestCategoryRepository
import com.example.myapplication.database.entities.Category
import com.example.myapplication.database.repository.CategoryRepository
import kotlinx.coroutines.flow.Flow

class CategoryViewModel (
    private val categoryRepository: CategoryRepository
): ViewModel() {
    companion object {
        val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory {
            override fun <T : ViewModel> create(
                modelClass: Class<T>,
                extras: CreationExtras
            ): T {

                val app: MyApp = (checkNotNull(extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY]) as MyApp)
                return CategoryViewModel(RestCategoryRepository(MyServerService.getInstance(), app.categoryRepository)) as T
            }
        }
    }

    suspend fun getAll(): List<Category> {
        return categoryRepository.getAll()
    }
}