package eu.friedcutlet.yokan.ui import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.util.nowMillis import kotlin.time.Instant import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.toLocalDateTime /** * Format an epoch-millis timestamp using the user's preferences from settings. * * - [DbSettings.relativeTimesTamps]: * * 0 — Off: always show the absolute date in [DbSettings.dateFormat]. * * 1 — Short: show Today / Yesterday. * * 2 — Long: show Today / Yesterday / N days ago for entries within the * last week. * Both relative modes fall back to the absolute date outside their relative * window so timestamps stay unambiguous. * * Returns "—" if [epochMillis] is non-positive (uninitialised/never-set). */ fun formatTimestamp( epochMillis: Long, dateFormat: String, relativeMode: Int, now: Long = nowMillis(), ): String { if (epochMillis <= 0L) return "—" val normalizedEpochMillis = normalizeEpochMillis(epochMillis) if (relativeMode != 0) { val date = epochToLocalDate(normalizedEpochMillis).date val today = epochToLocalDate(now).date val deltaDays = ((startOfDayMillis(today) - startOfDayMillis(date)) / 86_400_000L).toInt() when { deltaDays == 0 -> return "Today" deltaDays == 1 -> return "Yesterday" relativeMode == 2 && deltaDays in 2..6 -> return "$deltaDays days ago" relativeMode == 2 && deltaDays == 7 -> return "A week ago" } } return formatAbsoluteDate(normalizedEpochMillis, dateFormat) } /** Top-level convenience: format using the user's settings. */ fun formatTimestamp(settings: DbSettings, epochMillis: Long): String = formatTimestamp(epochMillis, settings.dateFormat, settings.relativeTimesTamps) /** Clock-only timestamp used by Mangayomi's history rows. */ fun formatClockTime(epochMillis: Long): String { if (epochMillis <= 0L) return "—" val local = epochToLocalDate(normalizeEpochMillis(epochMillis)) return "${local.hour.pad2()}:${local.minute.pad2()}" } /** * Format [epochMillis] as a date using the user-visible values from the * Appearance settings picker. * * The format string is the user-visible value from the settings picker. Any * unrecognised pattern falls back to ISO `yyyy-MM-dd` so we never crash on a * malformed value in storage. */ fun formatAbsoluteDate(epochMillis: Long, pattern: String): String { val ld = epochToLocalDate(normalizeEpochMillis(epochMillis)) val month = ld.month.ordinal + 1 val day = ld.day return when (pattern) { "M/d/y" -> "$month/$day/${ld.year}" "d/M/y" -> "$day/$month/${ld.year}" "y/M/d" -> "${ld.year}/$month/$day" "MM/dd/yy" -> "${month.pad2()}/${day.pad2()}/${ld.year.twoDigitYear()}" "dd/MM/yy" -> "${day.pad2()}/${month.pad2()}/${ld.year.twoDigitYear()}" "MM/dd/yyyy" -> "${month.pad2()}/${day.pad2()}/${ld.year}" "dd/MM/yyyy" -> "${day.pad2()}/${month.pad2()}/${ld.year}" "yyyy/MM/dd" -> "${ld.year}/${month.pad2()}/${day.pad2()}" "yyyy-MM-dd" -> "${ld.year}-${month.pad2()}-${day.pad2()}" "dd MMM yyyy" -> "${day.pad2()} ${monthShort(month)} ${ld.year}" "MMM d, y" -> "${monthShort(month)} $day, ${ld.year}" "MMM d, yyyy" -> "${monthShort(month)} $day, ${ld.year}" "MMM dd, yyyy" -> "${monthShort(month)} ${day.pad2()}, ${ld.year}" "MMMM d, yyyy" -> "${monthLong(month)} $day, ${ld.year}" else -> "${ld.year}-${month.pad2()}-${day.pad2()}" } } fun parseDateToEpochMillis(raw: String): Long? { val value = raw.trim() if (value.isBlank()) return null value.toLongOrNull()?.let { return normalizeEpochMillis(it) } val isoMatch = Regex("""(\d{4})-(\d{1,2})-(\d{1,2})""").find(value) ?: return null val (year, month, day) = isoMatch.destructured return runCatching { LocalDate(year.toInt(), month.toInt(), day.toInt()) .atStartOfDayIn(TimeZone.currentSystemDefault()) .toEpochMilliseconds() }.getOrNull() } private fun normalizeEpochMillis(value: Long): Long { val abs = kotlin.math.abs(value) return if (abs in 1L until 10_000_000_000L) value * 1000L else value } private fun startOfDayMillis(date: LocalDate): Long = date.atStartOfDayIn(TimeZone.currentSystemDefault()).toEpochMilliseconds() fun formatDecimal(value: Double, decimals: Int): String { val places = decimals.coerceAtLeast(0) var factor = 1L repeat(places) { factor *= 10L } val sign = if (value < 0) "-" else "" val scaled = kotlin.math.round(kotlin.math.abs(value) * factor).toLong() val whole = scaled / factor if (places == 0) return "$sign$whole" val fraction = (scaled % factor).toString().padStart(places, '0') return "$sign$whole.$fraction" } @OptIn(kotlin.time.ExperimentalTime::class) private fun epochToLocalDate(epochMillis: Long): LocalDateTime { val instant = Instant.fromEpochMilliseconds(epochMillis) return instant.toLocalDateTime(TimeZone.currentSystemDefault()) } private fun monthShort(month: Int): String = when (month) { 1 -> "Jan"; 2 -> "Feb"; 3 -> "Mar"; 4 -> "Apr"; 5 -> "May"; 6 -> "Jun" 7 -> "Jul"; 8 -> "Aug"; 9 -> "Sep"; 10 -> "Oct"; 11 -> "Nov"; 12 -> "Dec" else -> month.toString() } private fun monthLong(month: Int): String = when (month) { 1 -> "January"; 2 -> "February"; 3 -> "March"; 4 -> "April"; 5 -> "May"; 6 -> "June" 7 -> "July"; 8 -> "August"; 9 -> "September"; 10 -> "October"; 11 -> "November"; 12 -> "December" else -> month.toString() } private fun Int.pad2(): String = if (this < 10) "0$this" else toString() private fun Int.twoDigitYear(): String = (this % 100).pad2()