package com.applemand.zmanim.core.common

import kotlinx.datetime.Instant
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale

fun Instant.formatTime(
    tzid: String,
    twelveHour: Boolean,
    showSeconds: Boolean,
    locale: Locale = Locale.getDefault(),
): String {
    val zone = runCatching { ZoneId.of(tzid) }.getOrElse { ZoneId.systemDefault() }
    val pattern = when {
        twelveHour && showSeconds -> "h:mm:ss a"
        twelveHour -> "h:mm a"
        showSeconds -> "HH:mm:ss"
        else -> "HH:mm"
    }
    val fmt = DateTimeFormatter.ofPattern(pattern, locale).withZone(zone)
    return fmt.format(toJavaInstant())
}

fun Instant.toJavaInstant(): java.time.Instant = java.time.Instant.ofEpochMilli(toEpochMilliseconds())

fun LocalDate.atStartOfDayIn(tzid: String): Instant {
    val zone = TimeZone.of(tzid)
    return LocalDateTime(year, month, dayOfMonth, 0, 0, 0).toInstant(zone)
}
