package com.apps.quicksketchtrace.util

import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Point
import android.net.Uri
import android.provider.OpenableColumns
import android.util.DisplayMetrics
import android.util.Log
import android.view.MotionEvent
import android.view.WindowManager
import androidx.core.app.ActivityCompat
import androidx.core.graphics.createBitmap
import com.apps.quicksketchtrace.BApplication
import com.caverock.androidsvg.SVG
//import com.caverock.androidsvg.SVG
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import kotlin.math.min
import kotlin.math.sqrt

object OpenConvert {

    fun getShowPic(context: Context, name: String): String? {
        return try {
            val assetManager = context.assets
            val files = assetManager.list(name) ?: return null
            if (files.isNotEmpty()) {
                "$name/${files[0]}"
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }
    fun getAllPic(context: Context, name: String): List<String> {
        return try {
            val fileList = mutableListOf<String>()
            val assetManager = context.assets
            val files = assetManager.list(name)
            if (!files.isNullOrEmpty()) {
                for (file in files) {
                    fileList.add("$name/$file")
                }
            }
            fileList
        } catch (e: Exception) {
            emptyList()
        }
    }

    fun loadBitmapFromAssets(context: Context, fileName: String):Bitmap? {
        return if (fileName.endsWith(".svg", ignoreCase = true)) {
            loadSvgFromAssets(context, fileName)
        } else if(fileName.endsWith(".jpg")||fileName.endsWith(".png")) {
            loadRasterImageFromAssets(context, fileName)
        }else{
            null
        }

    }

    private fun loadRasterImageFromAssets(context: Context, fileName: String): Bitmap? {
        return try {
            context.assets.open(fileName).use { inputStream ->
                BitmapFactory.decodeStream(inputStream)
            }
        } catch (e:Exception){
            null
        }
    }

    private fun loadSvgFromAssets(context: Context, fileName: String): Bitmap? {
        return try {
            val svg = SVG.getFromAsset(context.assets, fileName)
            val documentWidth = svg.documentWidth
            val documentHeight = svg.documentHeight

            // Use default size if SVG doesn't specify dimensions
            val width = if (documentWidth > 0) documentWidth.toInt() else 800
            val height = if (documentHeight > 0) documentHeight.toInt() else 800

            val bitmap = createBitmap(width, height)
            val canvas = Canvas(bitmap)

            // Scale proportionally if needed
            if (documentWidth > 0 && documentHeight > 0) {
                val scale = min(width / documentWidth, height / documentHeight)
                canvas.scale(scale, scale)
            }

            svg.renderToCanvas(canvas)
            bitmap
        } catch (e: Exception) {
            null
        }
    }
    fun getUriFileSize(context: Context, uri: Uri): Double {
        var fileSize = 0.0
        val contentResolver = context.contentResolver

        // 如果Uri是文件类型
        if (uri.scheme == "file") {
            File(uri.path).let {
                fileSize = it.length().toDouble()
            }
        } else { // 如果Uri不是文件类型，则通过ContentResolver获取大小
            try {
                contentResolver.openFileDescriptor(uri, "r")?.use { pfd ->
                    fileSize = pfd.statSize.toDouble()
                }
            } catch (e: Exception) {
                Log.e("UriUtils", "Error while retrieving file size: ${e.message}")
            }
        }

        fileSize /= 1048576.0
        return fileSize
    }
    // 从URI获取文件名
    fun getFileNameFromUri(uri: Uri, context: Context): String? {
        var fileName: String? = null
        context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
            if (cursor.moveToFirst()) {
                val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                if (nameIndex != -1) fileName = cursor.getString(nameIndex)
            }
        }
        return fileName
    }

    fun getImportPath(name: String): String {
        val filesDir: File = BApplication.context.filesDir
        val s = "$filesDir/$name"
        return s
    }
    // 将URI内容复制到文件
    @Throws(IOException::class)
    fun copyUriToFile(uri: Uri, destFile: File, context: Context) {
        context.contentResolver.openInputStream(uri)?.use { inputStream ->
            FileOutputStream(destFile).use { outputStream ->
                val buffer = ByteArray(1024)
                var length: Int
                while (inputStream.read(buffer).also { length = it } > 0) {
                    outputStream.write(buffer, 0, length)
                }
            }
        } ?: throw IOException("Failed to open input stream for URI: $uri")
    }

    fun checkPermission(activity: Activity, permissions: Array<String>): Boolean {
        for (permission in permissions) {
            if (ActivityCompat.checkSelfPermission(
                    activity,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return true
            }
        }
        return false
    }
    fun getScreen(context: Context): Point {
        val displayMetrics = DisplayMetrics()
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        val width = displayMetrics.widthPixels
        val height = displayMetrics.heightPixels
        val point = Point()
        point.x = width
        point.y = height
        return point
    }
    fun getDistance(event: MotionEvent): Float {
        val x = event.getX(0) - event.getX(1)
        val y = event.getY(0) - event.getY(1)
        return sqrt((x * x + y * y).toDouble()).toFloat()
    }
}