package com.hello.wallpaper

import android.app.Activity
import android.app.WallpaperManager
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.Size
import androidx.window.layout.WindowMetricsCalculator
import androidx.work.*
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import java.io.File
import java.io.IOException

class GlideWallpaperWorker(
    context: Context,
    params: WorkerParameters
) : Worker(context, params) {

    override fun doWork(): Result {
        val imagePath = inputData.getString("imagePath") ?: return Result.failure()
        val wallpaperType = inputData.getInt("wallpaperType", 0)
        val desiredWidth = inputData.getInt("desiredWidth", 0)
        val desiredHeight = inputData.getInt("desiredHeight", 0)

        return try {
            Glide.with(applicationContext)
                .asBitmap()
                .load(File(imagePath))
                .apply(RequestOptions().override(desiredWidth, desiredHeight))
                .into(object : CustomTarget<Bitmap>() {
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        val wallpaperManager = WallpaperManager.getInstance(applicationContext)
                        try {
                            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                                wallpaperManager.setBitmap(resource)
                            } else {
                                when (wallpaperType) {
                                    0 -> wallpaperManager.setBitmap(resource, null, true, WallpaperManager.FLAG_SYSTEM)
                                    1 -> wallpaperManager.setBitmap(resource, null, true, WallpaperManager.FLAG_LOCK)
                                    2 -> {
                                        wallpaperManager.setBitmap(resource, null, true, WallpaperManager.FLAG_SYSTEM)
                                        wallpaperManager.setBitmap(resource, null, true, WallpaperManager.FLAG_LOCK)
                                    }
                                }
                            }
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                    }

                    override fun onLoadCleared(placeholder: Drawable?) {
                        // Handle cleanup if needed
                    }
                })
            Result.success()
        } catch (e: Exception) {
            e.printStackTrace()
            Result.retry()
        }
    }
}

// Trigger the WorkManager task
fun setWallpaperWithGlide(context: Context, activity: Activity, imagePath: String, wallpaperType: Int) {
    val screenSize: Size = getScreenDimensions(activity)
    val desiredWidth = screenSize.width * 2  // 适应横向滚动
    val desiredHeight = screenSize.height

    val inputData = Data.Builder()
        .putString("imagePath", imagePath)
        .putInt("wallpaperType", wallpaperType)
        .putInt("desiredWidth", desiredWidth)
        .putInt("desiredHeight", desiredHeight)
        .build()

    val setWallpaperRequest = OneTimeWorkRequest.Builder(GlideWallpaperWorker::class.java)
        .setInputData(inputData)
        .build()

    WorkManager.getInstance(context).enqueue(setWallpaperRequest)
}

// Modern method to get screen dimensions
private fun getScreenDimensions(activity: Activity): Size {
    val windowMetrics = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(activity)
    val bounds = windowMetrics.bounds
    val width = bounds.width()
    val height = bounds.height()
    return Size(width, height)
}