package pl.firmatpp.kierowca.data

import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import java.io.File
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import pl.firmatpp.kierowca.ui.theme.AppThemeMode

@OptIn(ExperimentalCoroutinesApi::class)
class AppPreferencesStoreTest {
    @get:Rule
    val temporaryFolder = TemporaryFolder()

    @Test
    fun startsWithMaterial3ThemeMode() = runTest {
        val store = preferencesStore("default.preferences_pb")

        assertEquals(AppThemeMode.Material3, store.themeMode.first())
    }

    @Test
    fun persistsSelectedThemeMode() = runTest {
        val file = temporaryFolder.newFile("theme.preferences_pb")
        val store = preferencesStore(file)

        store.setThemeMode(AppThemeMode.Material3)

        assertEquals(AppThemeMode.Material3, store.themeMode.first())
    }

    private fun TestScope.preferencesStore(fileName: String): AppPreferencesStore =
        preferencesStore(temporaryFolder.newFile(fileName))

    private fun TestScope.preferencesStore(file: File): AppPreferencesStore {
        val dataStore = PreferenceDataStoreFactory.create(scope = backgroundScope) { file }
        return AppPreferencesStore(dataStore)
    }
}
