package com.atmob.keyboard_android.ui.popup.base

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import android.widget.PopupWindow
import com.atmob.keyboard_android.ui.core.LayoutCallback

/**
 * 使用PopupWindow来实现弹窗
 */
abstract class BasePopupDialog(context: Context, private val hostWindow: Window) :
    LayoutCallback {
    private var mPopupWindow: PopupWindow? = null

    init {
        onLayoutBefore()

        // 填充布局
        val contentView = LayoutInflater.from(context).inflate(onInflaterViewId(), null, false)

        // 获取弹窗的宽高
        val frameSize = setupFrameSize()

        // 配置 PopupWindow
        mPopupWindow = PopupWindow(
            contentView,
            frameSize[0],
            frameSize[1]
        ).apply {
            // 不获取焦点，否则获取焦点会将软键盘关闭
            isFocusable = false
            // 保持输入法活跃
            inputMethodMode = PopupWindow.INPUT_METHOD_NEEDED
            // 点击外部区域，是否关闭弹窗
            isOutsideTouchable = isCanOutsideTouchable()
            // 设置背景，否则还是会关闭
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            setOnDismissListener(object : PopupWindow.OnDismissListener {
                override fun onDismiss() {
                    onDialogDismiss()
                }
            })
        }

        onInflaterViewAfter(contentView)
        onBindView(contentView)
        setData()
    }

    /**
     * 设置大小
     */
    private fun setupFrameSize(): IntArray {
        val decorView = hostWindow.decorView
        return onSetupDialogFrameSize(decorView.context, decorView.width, decorView.height)
    }

    /**
     * 显示Loading
     */
    fun show() {
        if (mPopupWindow?.isShowing == true) {
            return
        }

        // 显示在屏幕中央
        mPopupWindow?.showAtLocation(
            hostWindow.decorView,
            Gravity.CENTER,
            0,
            0
        )
    }

    override fun onLayoutBefore() {
    }

    override fun onInflaterViewAfter(view: View) {
    }

    override fun onBindView(view: View) {
    }

    override fun setData() {
    }

    /**
     * 获取弹窗的宽和高，默认铺满整个Window
     */
    protected open fun onSetupDialogFrameSize(
        context: Context,
        windowWidth: Int,
        windowHeight: Int
    ): IntArray {
        return intArrayOf(windowWidth, windowHeight)
    }

    /**
     * 是否允许点击外部区域，关闭弹窗
     */
    protected open fun isCanOutsideTouchable(): Boolean {
        return true
    }

    /**
     * 键盘关闭时回调
     */
    protected open fun onDialogDismiss() {
    }

    /**
     * 是否正在显示
     */
    fun isShowing(): Boolean {
        return mPopupWindow?.isShowing == true
    }

    /**
     * 隐藏Loading
     */
    fun dismiss() {
        mPopupWindow?.dismiss()
    }
}