package de.storchp.fdroidbuildstatus.utils

import androidx.core.net.toUri
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

object FormatUtils {
    fun formatShortDateTime(millis: Long): String {
        val normalizedMillis = when (millis) {
            // for some files we get seconds instead of millis normalizedMillis *= 1000
            in 1..9999999999 -> millis * 1000
            else -> millis
        }

        return SimpleDateFormat("dd/MM HH:mm", Locale.getDefault()).format(Date(normalizedMillis))
    }

    fun formatVersion(versionCode: Long?, versionName: String?): String {
        return ((versionCode?.toString() ?: "")
                + if (isEmpty(versionName)) "" else " - $versionName")
    }

    fun isEmpty(value: String?): Boolean {
        return value == null || value.trim { it <= ' ' }.isEmpty()
    }

    fun getNameFromSource(sourceCode: String?): String {
        try {
            return sourceCode?.toUri()?.lastPathSegment!!
        } catch (_: Exception) {
        }
        return ""
    }
}