package bou.amine.apps.readerforselfossv2.utils

import android.text.format.DateUtils
import io.github.aakira.napier.Napier
import kotlinx.datetime.*

actual class DateUtils {
    actual companion object {
        // Possible formats are
        // yyyy-mm-dd hh:mm:ss format
        private 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)
        private val newVersionFormat = "(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2})[+-](\\d{2}(:\\d{2})?)?".toRegex()

        // TODO: do not fix any more issues here. Move everything to plateform specific code.
        actual fun parseDate(dateString: String): Long {
            var isoDateString: String =
                try {
                    if (dateString.matches(oldVersionFormat)) {
                        dateString.replace(" ", "T")
                    } else if (dateString.matches(newVersionFormat)) {
                        newVersionFormat.find(dateString)?.groups?.get(1)?.value ?: throw Exception("Couldn't parse $dateString")
                    } else {
                        throw Exception("Unrecognized format for $dateString")
                    }
                } catch (e: Exception) {
                    throw Exception("parseDate failed for $dateString", e)
                }

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

        actual fun parseRelativeDate(dateString: String): String {
            val date = parseDate(dateString)

            return " " +
                DateUtils.getRelativeTimeSpanString(
                    date,
                    Clock.System.now().toEpochMilliseconds(),
                    DateUtils.MINUTE_IN_MILLIS,
                    DateUtils.FORMAT_ABBREV_RELATIVE,
                )
        }
    }
}
