package com.isidroid.utils

import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import android.provider.OpenableColumns
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

fun Uri.getDate(context: Context): Date {
    val cursor = context.contentResolver.query(this, null, null, null, null)
    val nameIndex = cursor?.getColumnIndex(OpenableColumns.DISPLAY_NAME) ?: -1
    val dateIndex = cursor?.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN) ?: -1
    cursor?.moveToFirst()
    val fileName = cursor?.getString(nameIndex)

    val formats = arrayOf(
        "MMM dd, yyyy HH-mm-ss",
        "MMM dd, yyyy",
        "yyyy-MM-dd",
        "dd-MM-yyyy",
        "dd-MMM-yy",
        "yyyy-MM-dd HH-mm-ss",
    )

    var d: Date? = null
    for (format in formats) {
        val dateFormat = SimpleDateFormat(format, Locale.getDefault())
        d = tryCatch { dateFormat.parse(fileName.orEmpty()) }
        if (d != null) break
    }

    val dateByFileTs = fileName
        .takeIf { it?.startsWith("img_") == true }
        ?.let { ("\\d+".toRegex().find(fileName.orEmpty())?.groups?.firstOrNull()?.value?.toLong()?.let { Date(it) }) }

    val date = d
        ?: dateByFileTs
        ?: tryCatch { cursor?.getLong(dateIndex) }?.let { Date(it) }
        ?: Date()

    cursor?.close()
    return date
}