package de.ladkau.deckinadash.data

import android.content.Context
import de.ladkau.deckinadash.nativebridge.DeckNative
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonNamingStrategy

/**
 * Computes a [ReadingDto] via [DeckNative], the single entry point both
 * the reading screen (ReadingViewModel) and the daily notification
 * (ReadingNotificationWorker) call - see NotificationScheduler's own
 * comment on why the notification must reuse this rather than
 * duplicating reading logic.
 */
class ReadingRepository(private val context: Context) {
    @OptIn(ExperimentalSerializationApi::class)
    private val json = Json {
        ignoreUnknownKeys = true
        namingStrategy = JsonNamingStrategy.SnakeCase
    }

    /** Directory DeckInADashApplication.onCreate() synced engine/i18n's .lang files into. */
    private val i18nDir: String
        get() = "${context.filesDir}/i18n"

    fun compute(config: DeckConfig, utcMomentEpochSeconds: Long): ReadingDto {
        val jsonText = DeckNative.generateReadingJson(
            birthYear = config.birthYear,
            birthMonth = config.birthMonth,
            birthDay = config.birthDay,
            birthHour = config.birthHour,
            birthMinute = config.birthMinute,
            utcOffsetHours = config.utcOffsetHours,
            latitude = config.latitude,
            longitude = config.longitude,
            gender = config.gender.ordinal,
            utcMomentEpochSeconds = utcMomentEpochSeconds,
            i18nDir = i18nDir,
            lang = config.lang,
        )
        return json.decodeFromString(ReadingDto.serializer(), jsonText)
    }
}
