package com.radiola.ui.history

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.radiola.domain.model.Track
import com.radiola.domain.repository.TrackHistoryRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class HistoryViewModel @Inject constructor(
    private val trackHistoryRepository: TrackHistoryRepository
) : ViewModel() {

    private val _searchQuery = MutableStateFlow("")
    val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()

    val history: StateFlow<List<Track>> = combine(
        trackHistoryRepository.getHistory(),
        _searchQuery
    ) { tracks, query ->
        if (query.isBlank()) tracks else tracks.filter {
            it.artist.contains(query, ignoreCase = true) ||
            it.song.contains(query, ignoreCase = true)
        }
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())

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

    fun removeTrack(track: Track) {
        viewModelScope.launch {
            trackHistoryRepository.removeTrack(track)
        }
    }
}
