package cy.hexor.furumi.data.local

import cy.hexor.furumi.domain.model.OfflineDownloadQueueState
import cy.hexor.furumi.domain.model.TrackCard
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class OfflineDownloadQueueStore @Inject constructor(
    private val libraryStore: OfflineLibraryStore
) {
    private val _state = MutableStateFlow(libraryStore.offlineDownloadQueueState())

    val state: StateFlow<OfflineDownloadQueueState> = _state.asStateFlow()

    @Synchronized
    fun enqueueDownloads(tracks: List<TrackCard>): OfflineDownloadQueueState {
        _state.value = libraryStore.enqueueOfflineDownloadTracks(tracks)
        return _state.value
    }

    @Synchronized
    fun nextPendingDownloadTrack(): TrackCard? {
        return libraryStore.nextPendingOfflineDownloadTrack()
    }

    @Synchronized
    fun markRunning(trackId: Long) {
        _state.value = libraryStore.markOfflineDownloadRunning(trackId)
    }

    @Synchronized
    fun markCompleted(trackId: Long) {
        _state.value = libraryStore.markOfflineDownloadCompleted(trackId)
    }

    @Synchronized
    fun markFailed(trackId: Long, error: String?) {
        _state.value = libraryStore.markOfflineDownloadFailed(trackId, error)
    }

    @Synchronized
    fun refresh() {
        _state.value = libraryStore.offlineDownloadQueueState()
    }
}
