package com.daodaoshi.chick_mood

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream

/**
 * 图片工具类
 * 用于处理图片加载、保存和URI转换
 */
object ImageUtils {

    private const val TAG = "ImageUtils"

    /**
     * 将URI转换为文件路径
     */
    suspend fun uriToFilePath(context: Context, uri: Uri): String? {
        return withContext(Dispatchers.IO) {
            try {
                val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
                context.contentResolver.query(uri, filePathColumn, null, null, null)?.use { cursor ->
                    val columnIndex = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                    cursor?.moveToFirst()
                    cursor?.getString(columnIndex ?: 0)
                }
            } catch (e: Exception) {
                Log.e(TAG, "转换URI到文件路径失败", e)
                null
            }
        }
    }

    /**
     * 将URI保存到应用私有存储
     */
    suspend fun saveImageToInternalStorage(context: Context, uri: Uri): String? {
        return withContext(Dispatchers.IO) {
            try {
                val inputStream: InputStream? = context.contentResolver.openInputStream(uri)
                val fileName = "image_${System.currentTimeMillis()}.jpg"
                val file = File(context.filesDir, fileName)

                inputStream?.use { input ->
                    FileOutputStream(file).use { output ->
                        input.copyTo(output)
                    }
                }

                Log.d(TAG, "图片保存成功: ${file.absolutePath}")
                file.absolutePath
            } catch (e: IOException) {
                Log.e(TAG, "保存图片失败", e)
                null
            }
        }
    }

    /**
     * 从文件路径加载Bitmap
     */
    suspend fun loadBitmapFromPath(imagePath: String): Bitmap? {
        return withContext(Dispatchers.IO) {
            try {
                val file = File(imagePath)
                if (file.exists()) {
                    BitmapFactory.decodeFile(file.absolutePath)
                } else {
                    Log.w(TAG, "图片文件不存在: $imagePath")
                    null
                }
            } catch (e: Exception) {
                Log.e(TAG, "加载图片失败", e)
                null
            }
        }
    }

    /**
     * 删除图片文件
     */
    fun deleteImageFile(imagePath: String): Boolean {
        return try {
            val file = File(imagePath)
            if (file.exists()) {
                file.delete()
                Log.d(TAG, "图片删除成功: $imagePath")
                true
            } else {
                Log.w(TAG, "图片文件不存在: $imagePath")
                true
            }
        } catch (e: Exception) {
            Log.e(TAG, "删除图片失败", e)
            false
        }
    }
}