package com.isidroid.utils

import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.provider.MediaStore
import android.provider.OpenableColumns
import android.webkit.MimeTypeMap
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.UUID

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
}

fun Uri.saveUriToInternalStorage(context: Context): File? {
    try {
        val extension = getFileExtensionFromUri(context)

        val inputStream: InputStream? = context.contentResolver.openInputStream(this)
        inputStream?.use { input ->
            val tempFile = File.createTempFile(UUID.randomUUID().toString(), ".${extension}", context.cacheDir)
            FileOutputStream(tempFile).use { output ->
                val buffer = ByteArray(4 * 1024)
                var read: Int
                while (input.read(buffer).also { read = it } != -1) {
                    output.write(buffer, 0, read)
                }
                output.flush()
            }
            return tempFile
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}

fun Uri.getFileExtensionFromUri(context: Context): String? {
    var extension: String? = null

    val mimeType = context.contentResolver.getType(this)
    if (mimeType != null) {
        extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType)
    }

    if (extension.isNullOrEmpty()) {
        val path = path
        if (path != null) {
            extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(File(path)).toString())
        }
    }

    return extension
}

fun Uri.getMimeType(context: Context): String? {
    var mimeType: String?
    mimeType = context.contentResolver.getType(this)
    if (mimeType == null) {
        val extension = fileExtension
        if (extension != null) {
            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
        }
    }
    return mimeType
}

 val Uri.fileExtension: String?
    get() {
        val path = path ?: return null
        val extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(File(path)).toString())
        return extension.ifEmpty { null }
    }

val String?.isMimeTypePdf get() = this == "application/pdf"
val String?.isMimeTypeImage get() = this?.startsWith("image/") == true

fun Uri.saveAsBitmapToFile(context: Context): File? {
    val bitmap = toBitmap(context) ?: return null
    return bitmap.saveToTempFile()
}

 fun Bitmap.saveToTempFile(): File {
    val file = File.createTempFile(UUID.randomUUID().toString(), ".jpg")
    saveToFile(file)
    recycle()

    return file
}

