package de.ladkau.deckinadash

import android.app.Application
import de.ladkau.deckinadash.data.ConfigRepository
import de.ladkau.deckinadash.notify.NotificationScheduler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.first
import java.io.File

/**
 * Copies assets/i18n's .lang files (synced at build time from engine/i18n/ -
 * see app/build.gradle.kts's syncI18n task) into filesDir/i18n/ once
 * per process start, since i18n_load() (linked into the native library
 * unchanged, see reading_json.c) needs real filesystem paths, not APK
 * assets. Also reschedules the daily notification on launch - one of
 * the two required call sites for NotificationScheduler.reschedule(),
 * see its own doc comment for the other (every config save).
 */
class DeckInADashApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        syncI18nAssets()

        CoroutineScope(Dispatchers.Default).launch {
            val config = ConfigRepository(this@DeckInADashApplication).config.first()
            if (config.configured) {
                NotificationScheduler.reschedule(this@DeckInADashApplication, config)
            }
        }
    }

    private fun syncI18nAssets() {
        val outDir = File(filesDir, "i18n").apply { mkdirs() }
        val files = assets.list("i18n") ?: return
        for (name in files) {
            assets.open("i18n/$name").use { input ->
                File(outDir, name).outputStream().use { output -> input.copyTo(output) }
            }
        }
    }
}
