package com.gh.ndownload.suspendwindow.window

import android.content.ComponentCallbacks
import android.content.Context
import android.content.res.Configuration
import android.graphics.PixelFormat
import android.os.Build
import android.view.View
import android.view.WindowManager

/**
 * 下载悬浮窗-Ui组件
 */
abstract class NDownloadSuspendWindow<T : View>(
    protected val context: Context,
    private val suspend: Boolean = true
) : ComponentCallbacks {

    private var _isAttached: Boolean = false

    val isAttached: Boolean get() = _isAttached

    protected val windowManager =
        context.getSystemService(Context.WINDOW_SERVICE) as WindowManager

    val root by lazy { create(context) }

    protected val layoutParams: WindowManager.LayoutParams = WindowManager.LayoutParams().apply {
        type = if (suspend) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            }
        } else {
            WindowManager.LayoutParams.TYPE_APPLICATION
        }
        format = PixelFormat.RGBA_8888
        flags =
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_FULLSCREEN
        onLayoutParamsCreated(this)
    }

    private fun create(context: Context): T =
        onCreateView(context).also {
            onViewCreated(it)
        }

    fun attach() {
        if (!isAttached) {
            try {
                _isAttached = true
                windowManager.addView(root, layoutParams)
                context.registerComponentCallbacks(this)
                onAttach()
            } catch (e: Throwable) {
                // 处理“Unable to add window android.view.ViewRootImpl$W@7bc9502 -- permission denied for window type 2038”的异常
                // 目前Sentry上仅Z10型号的手机报这个错误（Android 8.1.0），这里明明已经授予了SYSTEM_ALERT_WINDOW权限，但是就是会抛异常= =，只能暴力捕获处理了。。。
                // 相关异常的链接：https://sentry.shanqu.cc/organizations/lightgame/issues/407275/?project=22
                _isAttached = false
            }
        }
    }

    fun detach() {
        if (isAttached) {
            _isAttached = false
            onDetach()
            context.unregisterComponentCallbacks(this)
            windowManager.removeView(root)
        }
    }

    protected open fun onAttach() = Unit

    protected open fun onDetach() = Unit

    protected open fun onViewCreated(view: T) = Unit

    override fun onConfigurationChanged(configuration: Configuration) = Unit

    override fun onLowMemory() = Unit

    protected abstract fun onCreateView(context: Context): T

    protected abstract fun onLayoutParamsCreated(layoutParams: WindowManager.LayoutParams)
}