package com.tomhempel.rbarometer.utils

import java.util.Calendar
import java.util.Locale

/** Supported storage formats: YYYY, YYYY-MM, YYYY-MM-DD */
enum class DatePrecision(val wire: String) {
    YEAR("year"),
    YEAR_MONTH("year_month"),
    FULL("full");

    companion object {
        fun fromWire(value: String?): DatePrecision = when (value?.lowercase(Locale.ROOT)) {
            YEAR.wire -> YEAR
            YEAR_MONTH.wire -> YEAR_MONTH
            else -> FULL
        }

        fun detectStored(value: String?): DatePrecision {
            if (value.isNullOrBlank()) return FULL
            return when (value.count { it == '-' }) {
                0 -> YEAR
                1 -> YEAR_MONTH
                else -> FULL
            }
        }
    }
}

object DateAnswerFormat {

    data class Parsed(val year: Int, val month: Int = 1, val day: Int = 1)

    fun parseStored(value: String?): Parsed? {
        if (value.isNullOrBlank()) return null
        val parts = value.trim().split("-")
        val year = parts.getOrNull(0)?.toIntOrNull() ?: return null
        val month = parts.getOrNull(1)?.toIntOrNull() ?: 1
        val day = parts.getOrNull(2)?.toIntOrNull() ?: 1
        return Parsed(year, month.coerceIn(1, 12), day.coerceIn(1, 31))
    }

    fun format(precision: DatePrecision, year: Int, month: Int, day: Int): String = when (precision) {
        DatePrecision.YEAR -> year.toString()
        DatePrecision.YEAR_MONTH -> "%04d-%02d".format(year, month)
        DatePrecision.FULL -> "%04d-%02d-%02d".format(year, month, day)
    }

    /** Start of answer period as YYYYMMDD int for comparisons. */
    fun periodStart(value: String): Int {
        val p = parseStored(value) ?: return 0
        return p.year * 10000 + p.month * 100 + p.day
    }

    /** End of answer period as YYYYMMDD int for comparisons. */
    fun periodEnd(value: String): Int {
        val p = parseStored(value) ?: return 0
        return when (DatePrecision.detectStored(value)) {
            DatePrecision.YEAR -> p.year * 10000 + 1231
            DatePrecision.YEAR_MONTH -> {
                val cal = Calendar.getInstance()
                cal.set(p.year, p.month - 1, 1)
                val last = cal.getActualMaximum(Calendar.DAY_OF_MONTH)
                p.year * 10000 + p.month * 100 + last
            }
            DatePrecision.FULL -> p.year * 10000 + p.month * 100 + p.day
        }
    }
}
