package com.paperapp.lenscape.tools

import android.content.ContentValues
import android.content.Context
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.util.logging.Logger

object SetWayUtils {

    private val LOGGER = Logger.getLogger(SetWayUtils::class.java.name)

    interface ConnectCallBack {
        fun onResult(success: Boolean, inputStream: InputStream?)
    }

    fun downloadFile(url: String, savePath: String, callback: ConnectCallBack): Call {
        val client = OkHttpClient()
        val request = Request.Builder().url(url).build()
        val call = client.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                LOGGER.severe("Download failed: ${e.message}")
                callback.onResult(false, null)
            }

            override fun onResponse(call: Call, response: Response) {
                response.use {
                    try {
                        val responseBody = response.body
                        if (responseBody != null) {
                            val inputStream = responseBody.byteStream()
                            val writeSuccess = writeFile(inputStream, savePath)
                            callback.onResult(writeSuccess, inputStream)
                        } else {
                            LOGGER.warning("Empty response body")
                            callback.onResult(false, null)
                        }
                    } catch (e: Exception) {
                        LOGGER.severe("Error processing response: ${e.message}")
                        callback.onResult(false, null)
                    }
                }
            }
        })
        return call
    }

    private fun writeFile(inputStream: InputStream, filePath: String): Boolean {
        val file = File(filePath)
        return try {
            file.parentFile?.takeIf { !it.exists() }?.mkdirs()

            FileOutputStream(file).use { fos ->
                val buffer = ByteArray(4096)
                var bytesRead: Int
                while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                    fos.write(buffer, 0, bytesRead)
                }
                true
            }
        } catch (e: Exception) {
            LOGGER.severe("File write error: ${e.message}")
            false
        }
    }

    fun saveToGallery(context: Context, file: File): Uri? {
        val name = "${System.currentTimeMillis()}.jpg"
        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, name)
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                put(MediaStore.Images.Media.IS_PENDING, 1)
            }
        }
        val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        } else {
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        }
        val contentResolver = context.contentResolver
        val imgUri = contentResolver.insert(uri, contentValues) ?: run {
            Log.d("MediaSaver", "Failed to create media entry")
            return null
        }
        try {
            contentResolver.openOutputStream(imgUri)?.use { outputStream ->
                FileInputStream(file).use { inputStream ->
                    val buffer = ByteArray(4026)
                    var byteRead: Int
                    while (inputStream.read(buffer).also { byteRead = it } != -1) {
                        outputStream.write(buffer, 0, byteRead)
                    }
                }
            }?:run {
                Log.d("MediaSaver", "Failed to open output stream")
                return null
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                contentValues.clear()
                contentValues.put(MediaStore.Images.Media.IS_PENDING, 0)
                contentResolver.update(imgUri, contentValues, null, null)
            }

            return imgUri
        } catch (e: IOException) {
            Log.e("MediaSaver", "Error saving image to gallery", e)

            // 发生错误时删除创建的文件记录
            try {
                contentResolver.delete(imgUri, null, null)
            } catch (deleteEx: Exception) {
                Log.e("MediaSaver", "Failed to delete failed media entry", deleteEx)
            }

            return null
        }
    }
}