package com.rugvedsarika.privatelog.ui.home

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.asLiveData
import com.rugvedsarika.privatelog.data.model.Note
import com.rugvedsarika.privatelog.data.repository.NoteRepository
import kotlinx.coroutines.flow.flatMapLatest

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

    private val _searchQuery = kotlinx.coroutines.flow.MutableStateFlow("")
    
    val allNotes: LiveData<List<Note>> = _searchQuery
        .flatMapLatest { query ->
            if (query.isEmpty()) {
                repository.allNotes
            } else {
                repository.searchNotes(query)
            }
        }
        .asLiveData()

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

class HomeViewModelFactory(private val repository: NoteRepository) : 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")
    }
}
