package theorycrafter.utils

import androidx.compose.runtime.*
import androidx.compose.ui.SystemTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.jetbrains.skiko.currentSystemTheme


/**
 * Returns whether the system's color theme is a dark one.
 */
@Composable
@ReadOnlyComposable
fun isSystemThemeDark(): Boolean {
    return LocalSystemTheme.current == SystemTheme.Dark
}


/**
 * A composition local for the system theme.
 */
val LocalSystemTheme = staticCompositionLocalOf<SystemTheme> {
    error("System theme not provided")
}


/**
 * Provides the system theme.
 */
@Composable
fun ProvideSystemTheme(content: @Composable () -> Unit) {
    val systemTheme by produceState(initialValue = currentSystemTheme.asComposeSystemTheme()) {
        // Launch on a thread other than the event dispatching thread because tests typically
        // wait for the event dispatching thread to become idle.
        // Running this in the event dispatching thread means it will never be idle.
        launch(Dispatchers.IO) {
            while (true) {
                delay(1000)
                value = currentSystemTheme.asComposeSystemTheme()
            }
        }
    }

    CompositionLocalProvider(LocalSystemTheme provides systemTheme) {
        content()
    }
}


/**
 * Converts Skiko system theme type to Compose [SystemTheme].
 */
private fun org.jetbrains.skiko.SystemTheme.asComposeSystemTheme() : SystemTheme {
    return when (this) {
        org.jetbrains.skiko.SystemTheme.DARK -> SystemTheme.Dark
        org.jetbrains.skiko.SystemTheme.LIGHT -> SystemTheme.Light
        org.jetbrains.skiko.SystemTheme.UNKNOWN -> SystemTheme.Unknown
    }
}
