package com.keyboard.craft.util

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable
import android.net.Uri
import android.provider.Settings
import android.util.Xml
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import androidx.core.app.ShareCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.keyboard.craft.bean.MainDataBean
import jp.wasabeef.glide.transformations.BlurTransformation
import org.xmlpull.v1.XmlPullParser
import java.io.File
import java.io.StringReader
import kotlin.random.Random

fun getRandomInt(from: Int, until: Int): Int {
    var num = 0
    val random = Random.Default
    num = random.nextInt(from, until)
    return num
}

fun getRandomThumbUrl(data: List<MainDataBean>): String? {
    // 首先随机选择一个 MainDataBean
    val mainDataBean = data.randomOrNull()

    // 确保 mainDataBean 和 items 不为空
    val items = mainDataBean?.items ?: return null

    // 随机选择一个 ItemDataBean
    val itemDataBean = items.randomOrNull()

    // 返回对应的 thumbUrl
    return itemDataBean?.thumbUrl
}


fun getFileNameFromUrl(urlString: String): String {
    val uri = Uri.parse(urlString)
    val path = uri.path ?: urlString // 如果没有路径，将使用整个 URL
    val file = File(path)
    return file.name // 获取文件名部分
}

fun getSubDirectories(directory: File): List<String> {
    val subDirectories = mutableListOf<String>()

    if (directory.exists() && directory.isDirectory) {
        val subDirectoryFiles = directory.listFiles { file -> file.isDirectory }
        subDirectoryFiles?.forEach { subDir ->
            subDirectories.add(subDir.name)
        }
    }

    return subDirectories
}

fun removeFileExtension(fileName: String): String {
    return fileName.substringBeforeLast(".")
}

fun fileIsDownload(context: Context, zipUrl: String): Boolean {
    val destinationFolder = context.filesDir.absolutePath
    val childString = getFileNameFromUrl(zipUrl)
    val file = File(destinationFolder, removeFileExtension(childString))
    var getSubDirectories = ""
    if (file.exists() && file.isDirectory) {
        getSubDirectories = getSubDirectories(file)[0]
    }
    val sub = removeFileExtension(childString) + "/" + getSubDirectories
    val subFile = File(destinationFolder, sub)
    return subFile.exists()
}

fun currentlyThemeUFileString(context: Context, zipUrl: String): String {
    val destinationFolder = context.filesDir.absolutePath
    val childString = getFileNameFromUrl(zipUrl)
    val file = File(destinationFolder, removeFileExtension(childString))
    var getSubDirectories = ""
    if (file.exists() && file.isDirectory) {
        getSubDirectories = getSubDirectories(file)[0]
    }
    val sub = removeFileExtension(childString) + "/" + getSubDirectories
    return File(destinationFolder, sub).toString()
}

//输入法是否被启用
fun isMyInputMethodEnabled(context: Context): Boolean {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    val ids = imm.enabledInputMethodList.map { it.id }
    return ids.any { it.startsWith(context.packageName) }
}

//输入法是否被设置为默认输入法
fun isMyInputMethodDefault(context: Context): Boolean {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    val id =
        Settings.Secure.getString(context.contentResolver, Settings.Secure.DEFAULT_INPUT_METHOD)
    return id != null && id.startsWith(context.packageName)
}

fun loadRoundedImage(
    context: Context,
    imageUrl: String,
    imageView: ImageView,
    cornerRadius: Int = 10
) {
    val requestOptions = RequestOptions().transform(RoundedCorners(cornerRadius))

    Glide.with(context)
        .load(imageUrl)
        .apply(requestOptions)
        .into(imageView)
}

// 加载并给图片添加模糊效果的函数
fun loadAndBlurImage(
    context: Context,
    drawable: Drawable,
    imageView: ImageView,
    blurRadius: Int = 25
) {
    Glide.with(context)
        .load(drawable)
        .apply(RequestOptions.bitmapTransform(BlurTransformation(blurRadius)))
        .into(imageView)
}

fun getBitmapDrawable(context: Context, currentlyThemeUFile: String, name: String): Drawable {
    val imagePath = "$currentlyThemeUFile/res/drawable-xhdpi-v4/$name"
    val bitmap = BitmapFactory.decodeFile(imagePath)
    return BitmapDrawable(context.resources, bitmap)
}

fun getBitmapXXDrawable(context: Context, currentlyThemeUFile: String, name: String): Drawable {
    val imagePath = "$currentlyThemeUFile/res/drawable-xxhdpi-v4/$name"
    val bitmap = BitmapFactory.decodeFile(imagePath)
    return BitmapDrawable(context.resources, bitmap)
}

fun getRawVideoPath(currentlyThemeUFile: String): String {
    return "$currentlyThemeUFile/res/raw/keyboard_background_video.mp4"
}

fun getPath(currentlyThemeUFile: String, name: String): String {
    return "$currentlyThemeUFile/res/drawable-xhdpi-v4/$name"
}

fun getResColorsPath(currentlyThemeUFile: String): String {
    return "$currentlyThemeUFile/res/colors.xml"
}

fun colorsXmlPullParser(currentlyThemeUFile: String): Map<String, Int> {
    val colorsFile = File(getResColorsPath(currentlyThemeUFile)) // 构建文件对象
    val colorsMap = mutableMapOf<String, Int>()
    if (colorsFile.exists()) {
        val xmlContent = colorsFile.readText() // 读取文件内容为字符串
        val parser: XmlPullParser = Xml.newPullParser()
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
        parser.setInput(StringReader(xmlContent))

        var eventType = parser.eventType


        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG && (parser.name == "color" || parser.name == "item")) {
                val colorName = parser.getAttributeValue(null, "name")
                val colorValue = parser.nextText()

                // 只添加你需要的颜色到 map 中
                if (colorName == "key_text_color_normal" ||
                    colorName == "key_text_color_functional"
                ) {
                    colorsMap[colorName] = Color.parseColor(colorValue)
                }
            }
            eventType = parser.next()
        }

    } else {
    }
    return colorsMap
}

fun getStateDrawable(
    context: Context,
    defaultPath: String,
    pressedPath: String
): StateListDrawable {
    val defaultBitmap = BitmapFactory.decodeFile(defaultPath)
    val pressedBitmap = BitmapFactory.decodeFile(pressedPath)
    // 创建 StateListDrawable
    val stateListDrawable = StateListDrawable()
    val defaultDrawable = BitmapDrawable(context.resources, defaultBitmap)
    val pressedDrawable = BitmapDrawable(context.resources, pressedBitmap)
    // 添加按下状态
    val pressedState = intArrayOf(android.R.attr.state_pressed)
    stateListDrawable.addState(pressedState, pressedDrawable)
    // 添加默认状态
    val normalState = intArrayOf()
    stateListDrawable.addState(normalState, defaultDrawable)
    return stateListDrawable
}

fun openPrivacyPolicy(context: Context) {
    val privacyPolicyUrl = "https://sites.google.com/view/privacy-policy-html-app"

    val intent = Intent(Intent.ACTION_VIEW)
    intent.data = Uri.parse(privacyPolicyUrl)

    if (intent.resolveActivity(context.packageManager) != null) {
        context.startActivity(intent)
    }
}


fun shareAppInfo(context: Context) {
    val appPackageName = context.packageName
    val appInfo = context.packageManager.getApplicationInfo(appPackageName, PackageManager.GET_META_DATA)
    val appName = context.getString(appInfo.labelRes)

    val appPlayStoreLink = "https://play.google.com/store/apps/details?id=$appPackageName"

    val shareMessage = "Check out $appName on Google Play: $appPlayStoreLink"

    val shareIntent = ShareCompat.IntentBuilder.from(context as androidx.appcompat.app.AppCompatActivity)
        .setType("text/plain")
        .setText(shareMessage)
        .intent

    // 判断是否有可以处理分享的应用程序
    if (shareIntent.resolveActivity(context.packageManager) != null) {
        context.startActivity(shareIntent)
    }
}

fun openGooglePlayForReview(context: Context) {
    val packageName = context.packageName
    try {
        val intent = Intent(
            Intent.ACTION_VIEW,
            Uri.parse("https://play.google.com/store/apps/details?id=$packageName")
        )
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
    } catch (e: Exception) {
        // 如果设备上没有安装 Google Play 商店应用，则使用浏览器打开
        e.printStackTrace()
    }
}
