package bou.amine.apps.readerforselfossv2.utils

import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant

fun String.toParsedDate(): Long {
    // Possible formats are
    // yyyy-mm-dd hh:mm:ss format
    val oldVersionFormat = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(.()\\d*)?".toRegex()

    // yyyy-MM-dd'T'HH:mm:ss[.SSS]XXX (RFC3339)
    val newVersionFormat = "(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2})[+-](\\d{2}(:\\d{2})?)?".toRegex()

    val isoDateString: String =
        try {
            if (this.matches(oldVersionFormat)) {
                this.replace(" ", "T")
            } else if (this.matches(newVersionFormat)) {
                newVersionFormat.find(this)?.groups?.get(1)?.value ?: throw Exception("Couldn't parse $this")
            } else {
                throw Exception("Unrecognized format for $this")
            }
        } catch (e: Exception) {
            throw Exception("parseDate failed for $this", e)
        }

    return LocalDateTime.parse(isoDateString).toInstant(TimeZone.currentSystemDefault()).toEpochMilliseconds()
}

expect class DateUtils() {
    companion object {
        fun parseRelativeDate(dateString: String): String
    }
}
