package com.adealink.weparty.debug

import android.app.ActivityManager
import android.content.Context
import android.graphics.PixelFormat
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import com.adealink.frame.base.fastLazy

import com.adealink.frame.util.AppUtil
import com.adealink.frame.util.DisplayUtil
import com.adealink.frame.util.removeUiCallbacks
import com.adealink.frame.util.runOnUiThread
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.floatview.view.BaseDragFloatView
import com.adealink.weparty.databinding.LayoutMemoryUsageBinding

class SysMemoryUsageFloatView(floatData: SysMemoryUsageFloatData) : BaseDragFloatView(floatData) {

    private var binding: LayoutMemoryUsageBinding? = null
    private var startAvailableMemory: Long = 0
    private var minAvailableMemory: Long = Long.MAX_VALUE
    private var isStartDetect: Boolean = false
    private val activityManager by fastLazy {
        AppUtil.appContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    }
    private val detectRunnable by fastLazy {
        Runnable {
            val memoryInfo = ActivityManager.MemoryInfo()
            activityManager.getMemoryInfo(memoryInfo)
            val availMem = memoryInfo.availMem
            if (availMem < minAvailableMemory) {
                minAvailableMemory = availMem
            }
            scheduleDetect()
        }
    }

    override fun onCreate() {
        super.onCreate()
        val binding = LayoutMemoryUsageBinding.inflate(LayoutInflater.from(context))
        this.binding = binding
        setContentView(binding.root)
        binding.btnClose.setOnClickListener {
            removeSelf("")
        }
        binding.opBtn.setOnClickListener {
            if (isStartDetect) {
                //停止监控
                removeUiCallbacks(detectRunnable)
                binding.opBtn.text = "开始监控"
                showToast("监控期间最大系统内存增量为:${(formatSize(startAvailableMemory - minAvailableMemory))}")
                isStartDetect = false
                return@setOnClickListener
            }
            //开始监控
            isStartDetect = true
            binding.opBtn.text = "停止监控"
            val memoryInfo = ActivityManager.MemoryInfo()
            activityManager.getMemoryInfo(memoryInfo)
            startAvailableMemory = memoryInfo.availMem
            scheduleDetect()
        }
    }

    private fun scheduleDetect() {
        runOnUiThread(detectRunnable, 500)
    }

    override val windowParams = WindowManager.LayoutParams().apply {
        width = getLayoutParamWidth()
        height = getLayoutParamHeight()
        format = PixelFormat.TRANSLUCENT
        flags =
            WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
        gravity = Gravity.START or Gravity.TOP
        x = 0
        y = 0
    }

    override fun getLayoutParamWidth(): Int {
        return ViewGroup.LayoutParams.WRAP_CONTENT
    }

    override fun getLayoutParamHeight(): Int {
        return ViewGroup.LayoutParams.WRAP_CONTENT
    }

    override fun getClickableViews(): List<View>? {
        val binding = binding ?: return null
        return listOf(binding.btnClose, binding.opBtn)
    }

    override fun getLayoutParamX(): Int {
        return DisplayUtil.dp2px(20f)
    }

    override fun getLayoutParamY(): Int {
        return DisplayUtil.dp2px(71f)
    }

    override fun applySnapToEdge(): Boolean {
        return false
    }

    private fun formatSize(size: Long): String {
        var sizeFloat = size.toFloat()
        var suffix: String? = null

        if (size >= 1024) {
            suffix = "KB"
            sizeFloat /= 1024
            if (sizeFloat >= 1024) {
                suffix = "MB"
                sizeFloat /= 1024
                if (sizeFloat >= 1024) {
                    suffix = "GB"
                    sizeFloat /= 1024
                }
            }
        }

        val resultBuffer = StringBuilder(sizeFloat.toString())
        val commaOffset = resultBuffer.indexOf(".")
        if (commaOffset >= 0) {
            val decimalPoints = resultBuffer.length - commaOffset - 1
            if (decimalPoints > 2) {
                resultBuffer.setLength(commaOffset + 3)
            }
        }

        if (suffix != null) resultBuffer.append(suffix)
        return resultBuffer.toString()
    }

    override fun onDestroy() {
        super.onDestroy()
        removeUiCallbacks(detectRunnable)
    }

}