package com.rugvedsarika.shoplist.ui.home

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.rugvedsarika.shoplist.data.local.entities.ShoppingList
import com.rugvedsarika.shoplist.data.repository.ShopRepository
import kotlinx.coroutines.launch

import androidx.lifecycle.switchMap

class HomeViewModel(private val repository: ShopRepository) : ViewModel() {

    private val _searchQuery = androidx.lifecycle.MutableLiveData("")
    
    val allShoppingLists: LiveData<List<ShoppingList>> = _searchQuery.switchMap { query ->
        if (query.isBlank()) {
            repository.allShoppingLists
        } else {
            repository.searchShoppingLists(query)
        }
    }

    fun search(query: String) {
        _searchQuery.value = query
    }

    fun insert(shoppingList: ShoppingList) = viewModelScope.launch {
        repository.insertShoppingList(shoppingList)
    }

    fun delete(shoppingList: ShoppingList) = viewModelScope.launch {
        repository.deleteShoppingList(shoppingList)
    }

    fun update(shoppingList: ShoppingList) = viewModelScope.launch {
        repository.updateShoppingList(shoppingList)
    }
}

class HomeViewModelFactory(private val repository: ShopRepository) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(HomeViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return HomeViewModel(repository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}
