package com.audio.record.screen.test.tool

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.graphics.Color
import android.media.MediaMetadataRetriever
import android.os.Build
import android.os.Environment
import android.os.ParcelFileDescriptor
import android.util.DisplayMetrics
import android.util.Log
import android.util.TypedValue
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowManager
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.audio.record.screen.test.App
import com.audio.record.screen.test.tool.Extend.setMarginBottom
import java.io.File

object Common {
    val folderName = "ScreenRecording_Test"

    val videosFolderDir = Environment.DIRECTORY_MOVIES + "/${folderName}"
    val imagesFolderDir = Environment.DIRECTORY_PICTURES + "/${folderName}"

    fun getIcon(drawId: Int) = ContextCompat.getDrawable(App.instanceApp, drawId)

    fun showLog(msg: String) {
        Log.d(App.TAG, msg)
    }

    fun setStatusBarTextColor(activity: Activity, dark: Boolean) {
//        val window = activity.window
//        val decor = window.decorView
//
//        // 设置状态栏图标颜色（深色图标表示浅色背景）
//        var flags = decor.systemUiVisibility
//        flags = if (dark) {
//            flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
//        } else {
//            flags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
//        }
//        // 保持布局全屏
//        flags = flags or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//        decor.systemUiVisibility = flags
//
//        // 去除 TRANSLUCENT_STATUS，使用透明背景更现代
//        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
//        window.statusBarColor = Color.TRANSPARENT



        val window = activity.window
        val decor = window.decorView

        // 设置状态栏图标颜色：深色图标表示浅色背景
        var flags = decor.systemUiVisibility
        flags = if (dark) {
            flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        } else {
            flags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
        }

        // 保持布局延伸到状态栏区域
        flags = flags or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        decor.systemUiVisibility = flags

        // 去除旧的半透明标志，改为真正透明
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = Color.TRANSPARENT
    }




    fun dpToPx(dp: Int, context: Context): Int =
        TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dp.toFloat(),
            context.resources.displayMetrics,
        ).toInt()


    fun getScreenWH(context: Context): Pair<Int, Int> {
        val screenWidth = context.resources.displayMetrics.widthPixels
        val screenHeight = context.resources.displayMetrics.heightPixels

        return Pair(screenWidth, screenHeight)
    }

    /**
     * 在service中获取设备屏幕的实际像素尺寸（包含状态栏、导航栏）
     */
    fun getFullScreenSize(context: Context): Pair<Int, Int> {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11 (API 30)+
            val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val bounds = windowManager.maximumWindowMetrics.bounds
            Pair(bounds.width(), bounds.height())
        } else {
            // Android 10 及以下
            val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val metrics = DisplayMetrics()
            @Suppress("DEPRECATION")
            windowManager.defaultDisplay.getRealMetrics(metrics)
            Pair(metrics.widthPixels, metrics.heightPixels)
        }
    }


    fun getFull(context: Context): Pair<Int, Int> {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val realMetrics = DisplayMetrics()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            context.display?.getRealMetrics(realMetrics)
        } else {
            @Suppress("DEPRECATION")
            windowManager.defaultDisplay.getRealMetrics(realMetrics)
        }

        val realWidth = realMetrics.widthPixels
        val realHeight = realMetrics.heightPixels
        showLog("getScreenWH  realWidth=${realWidth} realHeight=${realHeight}")
        return Pair(realWidth, realHeight)
    }

    fun getNavigationBarHeight(context: Context): Int {
        val resources = context.resources
        val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
        return if (resourceId > 0 && hasNavigationBar(context)) {
            showLog("    fun getNavigationBarHeight  = ${resources.getDimensionPixelSize(resourceId)}")
            resources.getDimensionPixelSize(resourceId)
        } else {
            showLog("    fun getNavigationBarHeight  = 0")
            0
        }
    }

    fun hasNavigationBar(context: Context): Boolean {
        val id = context.resources.getIdentifier("config_showNavigationBar", "bool", "android")
        return if (id > 0) {
            context.resources.getBoolean(id)
        } else {
            // fallback 方法：判断是否有物理返回键（导航栏可能隐藏）
            val hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey()
            val hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK)
            !(hasMenuKey || hasBackKey)
        }
    }


    // 获取状态栏高度（兼容所有API）
    fun getStatusBarHeight(context: Context): Int {
        return when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> {
                val windowInsets = (context as? Activity)?.window?.decorView?.rootWindowInsets
                windowInsets?.stableInsetTop ?: getSystemStatusBarHeight(context)
            }

            else -> getSystemStatusBarHeight(context)
        }
    }

    private fun getSystemStatusBarHeight(context: Context): Int {
        val resources = context.resources
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        return if (resourceId > 0) {
            resources.getDimensionPixelSize(resourceId)
        } else {
            // 默认回退值（24dp是常见值）
            (24 * resources.displayMetrics.density).toInt()
        }
    }


    fun getAllImagePaths(directoryPath: String): List<String> {
        val imagePaths = mutableListOf<String>()
        val directory = File(directoryPath)

        if (directory.exists() && directory.isDirectory) {
            directory.walk().forEach { file ->
                if (file.isFile && isImageFile(file)) {
                    imagePaths.add(file.absolutePath)
                }
            }
        }

        return imagePaths
    }

    fun isImageFile(file: File): Boolean {
        val imageExtensions = listOf("jpg", "jpeg", "png", "bmp", "gif", "webp")
        val extension = file.extension.lowercase()
        return extension in imageExtensions
    }

    fun deleteAllFilesInDirectory(path: String) {
        val dir = File(path)
        if (dir.exists() && dir.isDirectory) {
            dir.listFiles()?.forEach { file ->
                if (file.isFile) {
                    file.delete()
                }
            }
        }
    }


    /**
     * 将缩略图按照 thumb_1、thumb_2排序返回
     */
    fun getNaturallySortedThumbFiles(path: String): List<String> {
        val dir = File(path)
        if (!dir.exists() || !dir.isDirectory) return emptyList()
        val files = dir.listFiles()
            ?.filter { it.isFile && it.name.startsWith("thumb_") }
            ?.sortedBy { extractNumberFromName(it.name) } ?: emptyList()
        return files.map {
            showLog("-----${it.absolutePath}")
            it.absolutePath
        }
    }

    // 提取文件名中的数字部分（如 thumb_5.jpg → 5）
    private fun extractNumberFromName(name: String): Int {
        val regex = Regex("thumb_(\\d+)")
        val match = regex.find(name)
        return match?.groupValues?.get(1)?.toIntOrNull() ?: Int.MAX_VALUE
    }

    /**
     * 计算视频时长，精确到毫秒
     */
    fun getVideoDurationMs(path: String): Long {
        val retriever = MediaMetadataRetriever()
        retriever.setDataSource(path)
        val duration =
            retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLong() ?: 0L
        retriever.release()
        return duration
    }

    fun millisToSeconds(millis: Long): String {
        val seconds = millis / 1000.0
        return String.format("%.1f", seconds)
    }


    /**
     * 毫秒数格式化时间格式 00：00：00.0
     */
    fun formatSeconds(ms: Float): String {
        val totalSeconds = ms / 1000f
        val hours = (totalSeconds / 3600).toInt()
        val minutes = ((totalSeconds % 3600) / 60).toInt()
        val seconds = (totalSeconds % 60).toInt()
        val tenth = ((totalSeconds - totalSeconds.toInt()) * 10).toInt() // 小数点后一位

        return String.format("%02d:%02d:%02d.%01d", hours, minutes, seconds, tenth)
    }

    /**
     * 毫秒数格式化时间格式 00：00：00
     */
    fun formatDuration(durationMs: Long): String {
        val totalSeconds = durationMs / 1000
        val hours = totalSeconds / 3600
        val minutes = (totalSeconds % 3600) / 60
        val seconds = totalSeconds % 60

        return String.format("%02d:%02d:%02d", hours, minutes, seconds)
    }
    /**
     * bytes格式化
     */
    fun formatFileSize(bytes: Long): String {
        val kb = 1024
        val mb = kb * 1024
        val gb = mb * 1024

        return when {
            bytes >= gb -> "%.2f GB".format(bytes / gb.toFloat())
            bytes >= mb -> "%.2f MB".format(bytes / mb.toFloat())
            bytes >= kb -> "%.2f KB".format(bytes / kb.toFloat())
            else -> "$bytes B"
        }
    }

    fun getVideoRatio(videoPath: String): Float {
        val retriever = MediaMetadataRetriever()
        retriever.setDataSource(videoPath)
        val width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)!!
            .toInt()
        val height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)!!
            .toInt()
        val aspectRatio = width.toFloat() / height
        retriever.release()
        return aspectRatio
    }

    fun getVideoWH(videoPath: String): Pair<Int, Int> {
        val retriever = MediaMetadataRetriever()
        retriever.setDataSource(videoPath)
        val width =
            retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)!!.toInt()
        val height =
            retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)!!.toInt()
        retriever.release()
        return Pair(width, height)
    }


    /**
     * 返回桌面
     */
    fun backHome(mContext: Context){
        val intent = Intent(Intent.ACTION_MAIN)
        intent.addCategory(Intent.CATEGORY_HOME)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        mContext.startActivity(intent)

    }


    /**
     * 时间转换格式
     */
    fun onRecordingTimeChanged(seconds: Long):String {
        val minutes = seconds / 60
        val sec = seconds % 60
        val formatted = String.format("%02d:%02d", minutes, sec)
//         showLog("Recorder  Recording duration: $formatted")
        return formatted
        // 示例：更新 UI TextView
        // binding.timerText.text = formatted
    }

    /**
     * 获取视频封面
     */
    fun getVideoThumbnail(pfd: ParcelFileDescriptor): Bitmap? {
        val retriever = MediaMetadataRetriever()
        try {
            retriever.setDataSource(pfd.fileDescriptor)
            // 获取第1帧，时间戳 0 微秒
            return retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC)
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        } finally {
            retriever.release()
        }
    }



      fun hideSystemUI(activity: Activity) {
          activity.window.decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
                    View.SYSTEM_UI_FLAG_FULLSCREEN or
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
    }

    fun enableImmersiveMode(activity: Activity) {
        // 允许内容扩展进系统栏区域
        WindowCompat.setDecorFitsSystemWindows(activity.window, false)

        val controller = WindowInsetsControllerCompat(activity.window, activity.window.decorView)

        // 隐藏状态栏和导航栏
        controller.hide(WindowInsetsCompat.Type.systemBars())

        // 沉浸式行为：滑动出现系统栏后自动隐藏
        controller.systemBarsBehavior =
            WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
    }

    fun enterFullScreen(activity: Activity) {
        activity.window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        activity.window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                )

        // 如果需要横屏播放：
//        activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
    }

    fun exitFullScreen(activity: Activity) {
        activity.window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
        activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    }


    fun setNavigation(rootView:View){
        ViewCompat.setOnApplyWindowInsetsListener(rootView) { view, insets ->
            val navBarInsets = insets.getInsets(WindowInsetsCompat.Type.navigationBars())
            val bottomPadding = navBarInsets.bottom
            view.setMarginBottom(bottomPadding)
//            view.setPadding(
//                view.paddingLeft,
//                view.paddingTop,
//                view.paddingRight,
//                bottomPadding // 系统判断好了该不该加 padding
//            )
            insets
        }

    }

}