package com.app.wave.keyboard.utils

import android.app.Activity
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import com.app.wave.keyboard.App
import com.bumptech.glide.Glide
import com.bumptech.glide.integration.webp.decoder.WebpDrawable
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import java.io.File

object Comutils {

    val transform = RequestOptions().transform(CenterCrop(), RoundedCorners(dpToPx(8f)))
    fun initFullScreen(activity: Activity, dark: Boolean? = true, showStatusBar: Boolean = false) {
        val window = activity.window
        val decorView = window.decorView

        if (showStatusBar) {
            // 显示状态栏，但保持透明
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                window.statusBarColor = Color.TRANSPARENT
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            }

            // 设置内容延伸到状态栏下
            var flags = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && dark == false) {
                flags = flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            }
            decorView.systemUiVisibility = flags
        } else {
            // 使用真正的全屏标志
            decorView.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_FULLSCREEN or
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    )

            // 移除状态栏的透明效果
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        }
    }


    fun loadWepJif(mContext: Context, webpGifUrl: String, view: ImageView) {
        Glide.with(mContext)
            .load(webpGifUrl)
//            .apply(transform)
            .addListener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable,
                    model: Any,
                    target: Target<Drawable>,
                    dataSource: DataSource,
                    isFirstResource: Boolean
                ): Boolean {
                    if (resource is WebpDrawable) {
                        resource.loopCount = WebpDrawable.LOOP_FOREVER
                    }
                    return false
                }
            }).into(view)
    }


    fun getBgDrawable(con: Context, filePath: String): Drawable? {
        if (!File(filePath).exists()) {
            return null
        }
        return BitmapDrawable(con.resources, BitmapFactory.decodeFile(filePath))
    }


    private val systemService =
        App.Companion.appInstance.getSystemService(Context.INPUT_METHOD_SERVICE)
    private val inputMethodManager = systemService as InputMethodManager
    fun checkSetDefault(con: Context): Boolean {
        // API 30+ 需要 QUERY_ALL_PACKAGES 权限
        return try {
            val defaultId =
                Settings.Secure.getString(con.contentResolver, Settings.Secure.DEFAULT_INPUT_METHOD)
            defaultId != null && defaultId.startsWith(con.packageName)
        } catch (e: SecurityException) {
            // API 30+ 可能没有权限访问
            Log.e("Comutils", "Permission denied to check default input method", e)
            false
        }
    }

    fun checkEnable(con: Context): Boolean {
        return try {
            // 总是使用传入的 context
            val inputMethodManager = con.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

            // 添加空值检查
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val enabledMethods = inputMethodManager.enabledInputMethodList
                enabledMethods.any { methodInfo ->
                    methodInfo.id.startsWith(con.packageName)
                }
            } else {
                // 旧版本的回退方案
                true // 假设已启用，避免阻塞
            }
        } catch (e: SecurityException) {
            Log.e("Comutils", "Permission denied checking enabled IMEs", e)
            // 在 API 30+ 上，如果没有权限，假设已启用
            true
        } catch (e: Exception) {
            Log.e("Comutils", "Error checking enabled IMEs", e)
            true // 出错时假设已启用，让用户继续
        }
    }

    fun getTextForImeAction(imeOptions: Int): Int {
        return imeOptions and EditorInfo.IME_MASK_ACTION
    }

    fun dpToPx(dpValue: Float): Int {
        val scale = App.Companion.appInstance.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }
}