package com.base.appzxhy.ui.deviceinfo

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.res.Configuration
import android.graphics.Camera
import android.graphics.ImageFormat
import android.graphics.Point
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.net.wifi.WifiManager
import android.os.Build
import android.os.storage.StorageManager
import android.util.DisplayMetrics
import android.view.Surface
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import com.base.appzxhy.R
import com.base.appzxhy.base.BaseActivity
import com.base.appzxhy.bean.DeviceDetailBean
import com.base.appzxhy.bean.DeviceInfoBean.Companion.BATTERY_INFORMATION
import com.base.appzxhy.bean.DeviceInfoBean.Companion.CAMERA_INFORMATION
import com.base.appzxhy.bean.DeviceInfoBean.Companion.DEVICE_INFORMATION
import com.base.appzxhy.bean.DeviceInfoBean.Companion.DISPLAY_INFORMATION
import com.base.appzxhy.bean.DeviceInfoBean.Companion.PROCESSOR_INFORMATION
import com.base.appzxhy.bean.DeviceInfoBean.Companion.RAM_INFORMATION
import com.base.appzxhy.bean.DeviceInfoBean.Companion.ROM_INFORMATION
import com.base.appzxhy.bean.DeviceInfoBean.Companion.WIFI_INFORMATION
import com.base.appzxhy.databinding.ActivityDeviceInfoDetailBinding
import com.base.appzxhy.databinding.ItemDeviceDetailBinding
import com.base.appzxhy.ui.adapter.CommonViewHolder
import com.base.appzxhy.utils.KotlinExt.toFormatSize
import com.base.appzxhy.utils.LogEx
import com.base.appzxhy.utils.Utils
import com.base.appzxhy.utils.XmlEx.inflate
import com.chad.library.adapter4.BaseQuickAdapter
import kotlinx.coroutines.async
import java.io.BufferedReader
import java.io.FileReader
import java.net.NetworkInterface
import java.util.Collections
import kotlin.math.roundToInt

class DeviceInfoDetailActivity : BaseActivity<ActivityDeviceInfoDetailBinding>(ActivityDeviceInfoDetailBinding::inflate) {

    companion object {
        var DeviceInfoKey = ""
    }

    val adapter = object : BaseQuickAdapter<DeviceDetailBean, CommonViewHolder>() {
        override fun onBindViewHolder(
            holder: CommonViewHolder,
            position: Int,
            item: DeviceDetailBean?
        ) {
            item ?: return
            binding.progressBar.visibility = View.GONE

            val itemBinding = ItemDeviceDetailBinding.bind(holder.itemView)
            itemBinding.tvTitle.text = item.title
            itemBinding.tvValue.text = item.value

        }

        override fun onCreateViewHolder(
            context: Context,
            parent: ViewGroup,
            viewType: Int
        ): CommonViewHolder {
            return CommonViewHolder(R.layout.item_device_detail.inflate(parent))
        }
    }

    override fun initView() {
        super.initView()
        binding.rv.adapter = adapter
        initData()
    }

    private fun initData() {
        when (DeviceInfoKey) {
            DEVICE_INFORMATION -> {
                getDeviceInformation()
            }

            PROCESSOR_INFORMATION -> {
                getProcessorInformation()
            }

            WIFI_INFORMATION -> {
                getWifiInformation()
            }

            DISPLAY_INFORMATION -> {
                getDisplayInformation()
            }

            RAM_INFORMATION -> {
                getRamInformation()
            }

            ROM_INFORMATION -> {
                getRomInformation()
            }

            CAMERA_INFORMATION -> {
                getCameraInformation()
            }
        }

    }

    private fun getCameraInformation() {
        val arrayList = arrayListOf<DeviceDetailBean>()

        val cameraManager = getSystemService(CAMERA_SERVICE) as CameraManager

        val frontDevice = DeviceDetailBean("Front Camera", "N/A")
        val rearDevice = DeviceDetailBean("Rear Camera", "N/A")

        val cameraIdList = cameraManager.cameraIdList


        cameraIdList.forEach {

            val characteristics = cameraManager.getCameraCharacteristics(it)
            val facing = characteristics.get(CameraCharacteristics.LENS_FACING)

            if (facing == CameraCharacteristics.LENS_FACING_FRONT) {
                val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
                val resolutions = map?.getOutputSizes(ImageFormat.JPEG)?.toList()
                val maxWith = resolutions?.maxOf { it.width } ?: 0
                val maxHeight = resolutions?.maxOf { it.height } ?: 0
                if (resolutions != null) {
                    val megapixels = (maxWith * maxHeight) / 1000000.0
                    frontDevice.value = "${maxWith}x${maxHeight}(${megapixels.roundToInt()} MP)"
                }
            }

            if (facing == CameraCharacteristics.LENS_FACING_BACK) {
                val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
                val resolutions = map?.getOutputSizes(ImageFormat.JPEG)?.toList()
                val maxWith = resolutions?.maxOf { it.width } ?: 0
                val maxHeight = resolutions?.maxOf { it.height } ?: 0
                if (resolutions != null) {
                    val megapixels = (maxWith * maxHeight) / 1000000.0
                    rearDevice.value = "${maxWith}x${maxHeight}(${megapixels.roundToInt()} MP)"
                }

            }
        }
        arrayList.add(frontDevice)
        arrayList.add(rearDevice)
        adapter.submitList(arrayList)
    }

    private fun getRomInformation() {
        val arrayList = arrayListOf<DeviceDetailBean>()

        val totalStorageSize = Utils.getTotalStorageSize()
        val availableStorageSize = Utils.getAvailableStorageSize()
        val usedStorageSize = totalStorageSize - availableStorageSize
        val percent = (100 * usedStorageSize / totalStorageSize)

        arrayList.add(DeviceDetailBean("Free ROM", availableStorageSize.toFormatSize()))
        arrayList.add(DeviceDetailBean("Used ROM", usedStorageSize.toFormatSize()))
        arrayList.add(DeviceDetailBean("Total ROM", totalStorageSize.toFormatSize()))
        arrayList.add(DeviceDetailBean("Percentage", "$percent %"))

        adapter.submitList(arrayList)
    }

    private fun getRamInformation() {
        val arrayList = arrayListOf<DeviceDetailBean>()

        val activityManager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)

        // 转换为MB
        val totalMem = memoryInfo.totalMem
        val availMem = memoryInfo.availMem
        val usedMem = totalMem - availMem
        val percent = (100 * usedMem / totalMem)

        arrayList.add(DeviceDetailBean("Free RAM", availMem.toFormatSize()))
        arrayList.add(DeviceDetailBean("Used RAM", usedMem.toFormatSize()))
        arrayList.add(DeviceDetailBean("Total RAM", totalMem.toFormatSize()))
        arrayList.add(DeviceDetailBean("Percentage", "$percent %"))

        adapter.submitList(arrayList)
    }

    private fun getDisplayInformation() {
        val arrayList = arrayListOf<DeviceDetailBean>()

        val windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
        val display = windowManager.defaultDisplay
        val fps = display.refreshRate.toInt()

        var orientation = "Portrait"
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
                val windowMetrics = windowManager.currentWindowMetrics
                val bounds = windowMetrics.bounds
                if (bounds.width() < bounds.height()) {
                    Configuration.ORIENTATION_PORTRAIT
                    orientation = "Portrait"
                } else {
                    Configuration.ORIENTATION_LANDSCAPE
                    orientation = "Landscape"
                }
            }

            else -> {
                val rotation = display.rotation
                val metrics = DisplayMetrics()
                display.getMetrics(metrics)

                val isNaturalPortrait = if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
                    metrics.heightPixels >= metrics.widthPixels
                } else {
                    metrics.widthPixels >= metrics.heightPixels
                }

                if (isNaturalPortrait) {
                    Configuration.ORIENTATION_PORTRAIT
                    orientation = "Portrait"
                } else {
                    Configuration.ORIENTATION_LANDSCAPE
                    orientation = "Landscape"
                }
            }
        }


        arrayList.add(DeviceDetailBean("Refresh Rate FPS", fps.toString()))
        arrayList.add(DeviceDetailBean("Default Orientation", orientation))
        val resolution = Point()
        display.getRealSize(resolution)
        arrayList.add(DeviceDetailBean("Width", "${resolution.x} px"))
        arrayList.add(DeviceDetailBean("Height", "${resolution.y} px"))

        adapter.submitList(arrayList)
    }

    @SuppressLint("DefaultLocale")
    private fun getWifiInformation() {
        val arrayList = arrayListOf<DeviceDetailBean>()

        val wifiManager = getSystemService(WIFI_SERVICE) as WifiManager
        val wifiInfo = wifiManager.connectionInfo
        val ipAddress = wifiInfo.ipAddress

        val ip = if (ipAddress == 0) {
            "<unknown ip>"
        } else {
            String.format(
                "%d.%d.%d.%d",
                ipAddress and 0xff,
                ipAddress shr 8 and 0xff,
                ipAddress shr 16 and 0xff,
                ipAddress shr 24 and 0xff
            )
        }
        arrayList.add(DeviceDetailBean("Ip Address", ip))

        val ssi = if (wifiInfo.bssid != null) {
            wifiInfo.rssi.toString() + " dBm"  // 返回信号强度值 (dBm)
        } else {
            "<unknown ssid>" // 未连接Wi-Fi
        }
        arrayList.add(DeviceDetailBean("SSI", ssi))

        var macValue = "N/A"
        val interfaces = Collections.list(NetworkInterface.getNetworkInterfaces())
        interfaces.forEach {
            LogEx.logDebug(TAG, "${it.name} ${it.hardwareAddress}")
        }
        runCatching {
            interfaces.firstOrNull { it.name.equals("wlan0", ignoreCase = true) }?.hardwareAddress?.let { mac ->
                macValue = mac.joinToString(":") { String.format("%02X", it) }
            }
        }
        arrayList.add(DeviceDetailBean("MAC Address", macValue))

        adapter.submitList(arrayList)

    }

    private fun getProcessorInformation() {
        val arrayList = arrayListOf<DeviceDetailBean>()

        val abi = Build.SUPPORTED_64_BIT_ABIS.firstOrNull() ?: Build.SUPPORTED_ABIS.firstOrNull() ?: Build.CPU_ABI ?: "unknown"
        var core = 1
        runCatching { core = Runtime.getRuntime().availableProcessors() }
        val s = if (core > 1) "Cores" else "Core"
        arrayList.add(DeviceDetailBean("Process", "$abi $core $s"))
        arrayList.add(DeviceDetailBean("Cores Number", "$core"))

        var mhz = "N/A"
        runCatching {
            val reader = BufferedReader(FileReader("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"))
            val freq = reader.readLine().trim()
            reader.close()
            mhz = "${freq.toInt() / 1000}"
        }

        arrayList.add(DeviceDetailBean("CPU Settings", "$mhz MHz"))

        adapter.submitList(arrayList)

    }

    private fun getDeviceInformation() {
        val arrayList = arrayListOf<DeviceDetailBean>()

        val windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
        val display = windowManager.defaultDisplay
        val resolution = Point()
        display.getRealSize(resolution)

        arrayList.add(
            DeviceDetailBean("Screen Resolution", "${resolution.x}x${resolution.y}")
        )

        val displayMetrics = resources.displayMetrics
        val widthInches = displayMetrics.widthPixels / displayMetrics.xdpi
        val heightInches = displayMetrics.heightPixels / displayMetrics.ydpi
        arrayList.add(
            DeviceDetailBean("Screen Size", "${"%.0f".format(widthInches)}x${"%.0f".format(heightInches)} inches")
        )

        arrayList.add(DeviceDetailBean("Model Number", "${Build.MODEL}"))
        arrayList.add(DeviceDetailBean("Android version", "${Build.VERSION.RELEASE}"))

        adapter.submitList(arrayList)
    }

    override fun initListener() {
        super.initListener()
        binding.ivBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
    }

    override fun handleBackCallBack() {
        finish()
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)
    }


}