package com.qimai.android.widgetlib.popup

import android.content.Context
import android.graphics.Color
import android.graphics.Point
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.*
import android.widget.FrameLayout
import android.widget.PopupWindow
import androidx.core.view.ViewCompat

/**
 *   created by wangwei   ON 2019-08-22  email:wangwei_5521@163.com
 *   @version 1.1.1
 *   @Description
 **/
@Deprecated("please use AbsQMBasePopup replace")
abstract class QMBasePopup(open var context: Context) {


    private var mWindow = PopupWindow()

    private lateinit var mRootViewWrapper: FrameLayout
    private var mBackground: Drawable? = null
    private lateinit var mWindowManager: WindowManager

    private var mWindowWidth = ViewGroup.LayoutParams.MATCH_PARENT
    private var mWindowHeight = ViewGroup.LayoutParams.WRAP_CONTENT
    open var gravity = Gravity.NO_GRAVITY

    protected open var mDismissListener: PopupWindow.OnDismissListener? = null

    fun setWindowWidth(windowWidth: Int) {
        this.mWindowWidth = windowWidth
    }

    fun setWindowHeight(windowHeight: Int) {
        this.mWindowHeight = windowHeight
    }

    fun setAnimationStyle(style: Int) {
        mWindow.animationStyle = style
    }


    fun isShowing(): Boolean {
        return mWindow.isShowing
    }

    fun dimBehind(dim: Float) {
        if (!::mWindowManager.isInitialized)
            mWindowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        if (!isShowing()) {
            throw RuntimeException("should call after method show() or in onShowEnd()")
        }
        val decorView = getDecorView()
        if (decorView != null) {
            val p = decorView.layoutParams as WindowManager.LayoutParams
            p.flags = p.flags or WindowManager.LayoutParams.FLAG_DIM_BEHIND
            p.dimAmount = dim
            mWindowManager.updateViewLayout(decorView, p)
        }
    }

    protected abstract fun onShowBegin(parent: View, attachedView: View?): Point

    protected fun onShowEnd() {}


    fun dismiss() {
        mWindow.dismiss()
    }

    fun show(parent: View) {
        show(parent, null)
    }


    fun show(parent: View, anchorView: View?) {

        if (anchorView != null && !ViewCompat.isAttachedToWindow(anchorView)) {
            return
        }
        mWindow.width = mWindowWidth
        mWindow.height = mWindowHeight
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            mWindow.isAttachedInDecor = false
        }
        val point = onShowBegin(parent, anchorView)

        mWindow.showAtLocation(parent, gravity, point.x, point.y)

        onShowEnd()

        // 在相关的View被移除时，window也自动移除。避免当Fragment退出后，Fragment中弹出的PopupWindow还存在于界面上。
        parent.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
            override fun onViewAttachedToWindow(v: View) {

            }

            override fun onViewDetachedFromWindow(v: View) {
                if (isShowing()) {
                    dismiss()
                }
            }
        })
    }


    protected fun onShowConfig() {

        if (mBackground == null) {
            mWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        } else {
            mWindow.setBackgroundDrawable(mBackground)
        }

        mWindow.isTouchable = true
        mWindow.isFocusable = true
        mWindow.isOutsideTouchable = true
    }

    fun setContentView(root: View) {
        mRootViewWrapper = FrameLayout(root.context)
        mRootViewWrapper.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        mRootViewWrapper.addView(root)
        mWindow.contentView = mRootViewWrapper

        onShowConfig()
        mWindow.setTouchInterceptor(View.OnTouchListener { v, event ->
            if (event.action == MotionEvent.ACTION_OUTSIDE) {
                mWindow.dismiss()
                return@OnTouchListener false
            }
            false
        })
        mWindow.setOnDismissListener {
            this@QMBasePopup.onDismiss()
            if (mDismissListener != null) {
                mDismissListener!!.onDismiss()
            }
        }
    }

    protected fun onDismiss() {}

    private fun getDecorView(): View? {
        var decorView: View? = null
        try {
            decorView = if (mWindow.background == null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mWindow.contentView.parent as View
                } else {
                    mWindow.contentView
                }
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mWindow.contentView.parent.parent as View
                } else {
                    mWindow.contentView.parent as View
                }
            }
        } catch (ignore: Exception) {

        }

        return decorView
    }

}