package com.example.base.extensions

import android.annotation.SuppressLint
import android.content.ContentValues
import android.graphics.Bitmap
import android.graphics.BitmapFactory.decodeFile
import android.net.Uri
import android.provider.MediaStore
import android.text.TextUtils
import androidx.core.content.FileProvider
import com.example.base.utils.Utils
import java.io.File
import java.util.Locale


/**
 * file扩展工具类
 */

fun File?.rename(newName: String): Boolean {
    // file is null then return false
    if (this == null) return false
    // file doesn't exist then return false
    if (!this.exists()) return false
    // the new name equals old name then return true
    if (newName == this.name) return true
    val newFile = File("${this.parent}${File.separator}$newName")
    // the new name of file exists then return false
    return (!newFile.exists() && this.renameTo(newFile))
}


/**
 * file 转 uri 7。0授权
 *
 * @return Uri
 */
fun File.toGrantUri(): Uri {

    return FileProvider.getUriForFile(
        Utils.getApp(),
        "${Utils.getApp().packageName}.fileProvider",
        this
    )
}

/**
 * 获取bitmap
 *
 * @return bitmap
 */
fun File.getBitmap(): Bitmap? = decodeFile(this.absolutePath)


/**
 * 自动压缩图片压缩
 * @return File?
 */
/*fun File.compressImage(): File? {

    // /storage/emulated/0/Android/data/当前应用包名/cache/Pictures/UUID随机数.jpg
    val cacheDir = Utils.getApp().externalCacheDir
    val resultDir = File(cacheDir, Environment.DIRECTORY_PICTURES)
    if (!resultDir.mkdirs() && (!resultDir.exists() || !resultDir.isDirectory)) {
        return null
    }
    val tagImg = File(resultDir, "${UUID.randomUUID()}.jpg")
    val bool = ImageCompressEngine(this, tagImg).compress()
    return if (bool) tagImg else null
}*/

fun File.isJpeg(): Boolean = this.absolutePath.contains("jpeg") || this.absolutePath.contains("jpg")


fun File.getMIMEType(): String {
    var type = "*/*"
    val fName = this.name

    //获取后缀名前的分隔符"."在fName中的位置。
    val dotIndex = fName.lastIndexOf(".")
    if (dotIndex < 0) {
        return type
    }

    /* 获取文件的后缀名*/
    val end = fName.substring(dotIndex, fName.length).toLowerCase(Locale.ROOT)
    if (TextUtils.isEmpty(end)) {
        return type
    }

    //在MIME和文件类型的匹配表中找到对应的MIME类型。
    for (i in MIME_MapTable.indices) {
        if (end == MIME_MapTable[i][0]) {
            type = MIME_MapTable[i][1]
            break
        }
    }
    return type
}


/**
 *
 * 绝对路径转uri
 *
 * @return content Uri
 */
@SuppressLint("Recycle", "Range")
fun File.getAbsolutePath(): Uri? {
    val filePath = this.absolutePath
    val cursor = Utils.getApp().contentResolver.query(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
        arrayOf(MediaStore.Images.Media._ID), MediaStore.Images.Media.DATA + "=? ",
        arrayOf(filePath), null
    )
    return if (cursor != null && cursor.moveToFirst()) {
        val id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
        val baseUri = Uri.parse("content://media/external/images/media")
        cursor.closeQuietly()
        Uri.withAppendedPath(baseUri, "" + id)
    } else {
        cursor?.closeQuietly()
        if (this.exists()) {
            val values = ContentValues()
            values.put(MediaStore.Images.Media.DATA, filePath)
            Utils.getApp().contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                values
            )
        } else {
            null
        }
    }
}


private val MIME_MapTable = arrayOf(
    // {后缀名，MIME类型}
    arrayOf(".3gp", "video/3gpp"),
    arrayOf(".apk", "application/vnd.android.package-archive"),
    arrayOf(".asf", "video/x-ms-asf"),
    arrayOf(".avi", "video/x-msvideo"),
    arrayOf(".bin", "application/octet-stream"),
    arrayOf(".bmp", "image/bmp"),
    arrayOf(".c", "text/plain"),
    arrayOf(".class", "application/octet-stream"),
    arrayOf(".conf", "text/plain"),
    arrayOf(".cpp", "text/plain"),
    arrayOf(".doc", "application/msword"),
    arrayOf(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
    arrayOf(".xls", "application/vnd.ms-excel"),
    arrayOf(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
    arrayOf(".exe", "application/octet-stream"),
    arrayOf(".gif", "image/gif"),
    arrayOf(".gtar", "application/x-gtar"),
    arrayOf(".gz", "application/x-gzip"),
    arrayOf(".h", "text/plain"),
    arrayOf(".htm", "text/html"),
    arrayOf(".html", "text/html"),
    arrayOf(".jar", "application/java-archive"),
    arrayOf(".java", "text/plain"),
    arrayOf(".jpeg", "image/jpeg"),
    arrayOf(".jpg", "image/jpeg"),
    arrayOf(".js", "application/x-javascript"),
    arrayOf(".log", "text/plain"),
    arrayOf(".m3u", "audio/x-mpegurl"),
    arrayOf(".m4a", "audio/mp4a-latm"),
    arrayOf(".m4b", "audio/mp4a-latm"),
    arrayOf(".m4p", "audio/mp4a-latm"),
    arrayOf(".m4u", "video/vnd.mpegurl"),
    arrayOf(".m4v", "video/x-m4v"),
    arrayOf(".mov", "video/quicktime"),
    arrayOf(".mp2", "audio/x-mpeg"),
    arrayOf(".mp3", "audio/x-mpeg"),
    arrayOf(".mp4", "video/mp4"),
    arrayOf(".mpc", "application/vnd.mpohun.certificate"),
    arrayOf(".mpe", "video/mpeg"),
    arrayOf(".mpeg", "video/mpeg"),
    arrayOf(".mpg", "video/mpeg"),
    arrayOf(".mpg4", "video/mp4"),
    arrayOf(".mpga", "audio/mpeg"),
    arrayOf(".msg", "application/vnd.ms-outlook"),
    arrayOf(".ogg", "audio/ogg"),
    arrayOf(".pdf", "application/pdf"),
    arrayOf(".png", "image/png"),
    arrayOf(".pps", "application/vnd.ms-powerpoint"),
    arrayOf(".ppt", "application/vnd.ms-powerpoint"),
    arrayOf(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"),
    arrayOf(".prop", "text/plain"),
    arrayOf(".rc", "text/plain"),
    arrayOf(".rmvb", "audio/x-pn-realaudio"),
    arrayOf(".rtf", "application/rtf"),
    arrayOf(".sh", "text/plain"),
    arrayOf(".tar", "application/x-tar"),
    arrayOf(".tgz", "application/x-compressed"),
    arrayOf(".txt", "text/plain"),
    arrayOf(".wav", "audio/x-wav"),
    arrayOf(".wma", "audio/x-ms-wma"),
    arrayOf(".wmv", "audio/x-ms-wmv"),
    arrayOf(".wps", "application/vnd.ms-works"),
    arrayOf(".xml", "text/plain"),
    arrayOf(".z", "application/x-compress"),
    arrayOf(".zip", "application/x-zip-compressed"),
    arrayOf("", "*/*")
)




