package com.applemand.zmanim.core.zmanim

import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale

class ZmanimFormatter(
    private val tzid: String,
    private val twelveHour: Boolean = true,
    private val showSeconds: Boolean = false,
    private val locale: Locale = Locale.getDefault(),
) {
    private val pattern: String = when {
        twelveHour && showSeconds -> "h:mm:ss a"
        twelveHour -> "h:mm a"
        showSeconds -> "HH:mm:ss"
        else -> "HH:mm"
    }
    private val zone: ZoneId = runCatching { ZoneId.of(tzid) }.getOrElse { ZoneId.systemDefault() }
    private val fmt: DateTimeFormatter = DateTimeFormatter.ofPattern(pattern, locale).withZone(zone)

    fun format(epochMs: Long?): String {
        if (epochMs == null) return EMPTY
        return fmt.format(Instant.ofEpochMilli(epochMs))
    }

    companion object {
        const val EMPTY = "—"
    }
}
