package com.hello.wallpaper

import android.app.Activity
import android.app.WallpaperManager
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.util.Size
import androidx.window.layout.WindowMetricsCalculator
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class SetWallpaperPlugin : FlutterPlugin, ActivityAware, MethodChannel.MethodCallHandler {
    private lateinit var context: Context
    private lateinit var channel: MethodChannel
    private lateinit var activity: Activity

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "set_wallpaper")
        context = flutterPluginBinding.applicationContext
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (call.method == "setWallpaper") {
            val path = call.argument<String>("path")
            val wallpaperType = call.argument<Int>("wallpaperType") // 0 for home screen, 1 for lock screen, 2 for both

            if (path != null && wallpaperType != null) {
                setWallpaper(path, wallpaperType, result)
            }
        } else {
            result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
    }

    override fun onDetachedFromActivityForConfigChanges() {
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        activity = binding.activity
    }

    override fun onDetachedFromActivity() {
    }

    @OptIn(DelicateCoroutinesApi::class)
    fun setWallpaper(path: String, wallpaperType: Int, result: MethodChannel.Result) {
        val screenSize: Size = getScreenDimensions()
        val desiredWidth = screenSize.width * 2  // 适应横向滚动
        val desiredHeight = screenSize.height

        GlobalScope.launch(Dispatchers.IO) {
            val wallpaperManager = WallpaperManager.getInstance(context)
            try {
                val largeBitmap = BitmapFactory.decodeFile(path)
                val scaledBitmap = Bitmap.createScaledBitmap(largeBitmap, desiredWidth, desiredHeight, true)
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                    wallpaperManager.setBitmap(scaledBitmap)
                } else {
                    when (wallpaperType) {
                        0 -> wallpaperManager.setBitmap(largeBitmap, null, true, WallpaperManager.FLAG_SYSTEM)
                        1 -> wallpaperManager.setBitmap(largeBitmap, null, true, WallpaperManager.FLAG_LOCK)
                        2 -> {
                            wallpaperManager.setBitmap(largeBitmap, null, true, WallpaperManager.FLAG_SYSTEM)
                            wallpaperManager.setBitmap(largeBitmap, null, true, WallpaperManager.FLAG_LOCK)
                        }
                    }
                }
                largeBitmap.recycle()
                scaledBitmap.recycle()
                result.success("Wallpaper applied successfully")
            } catch (e: Exception) {
                result.error("ERROR", "Failed to set wallpaper: ${e.message}", null)
            }
        }
    }

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