package com.ama.core.architecture.widget

import android.app.Activity
import android.app.Dialog
import android.content.DialogInterface
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.RoundRectShape
import android.os.Bundle
import android.util.SparseArray
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.annotation.IdRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.viewbinding.ViewBinding
import com.ama.core.architecture.R
import com.ama.core.architecture.util.ScreenUtils
import com.ama.core.architecture.util.eventbus.NotifyMan
import com.ama.core.common.util.dp


open class BindingDialog<VB : ViewBinding>(protected val mActivity: Activity,
                                           private val inflate: (LayoutInflater) -> VB,
                                           themeResId: Int = R.style.LDialog) : Dialog(mActivity, themeResId), LifecycleEventObserver {
    private val views = SparseArray<View>()
    private var width = 0
    private var height = 0
    private var bgRadius = 0 //背景圆角

    private var leftTopRadius = 0
    private var rightTopRadius = 0
    private var leftBottomRadius = 0
    private var rightBottomRadius = 0
    private var bgColor = Color.TRANSPARENT //背景颜色

    lateinit var mBinding: VB
    var currEvent: Lifecycle.Event? = null

    private var mEventCallback: NotifyMan.ICallback? = null

    protected fun registerEvents(onEvents: ((NotifyMan.NotifyData<*>?)->Unit), vararg eventTypes: Int) {
        if (mEventCallback == null) {
            mEventCallback = object : NotifyMan.ICallback(true) {
                override fun onEvent(data: NotifyMan.NotifyData<*>?) {
                    onEvents.invoke(data)
                }
            }
        }

        NotifyMan.instance().register(mEventCallback, *eventTypes)
    }

    companion object {

        fun getRoundRectDrawable(radius: Int, color: Int): ShapeDrawable {
            return getRoundRectDrawable(radius, radius, radius, radius, color)
        }

        fun getRoundRectDrawable(leftTop: Int, rightTop: Int, rightBottom: Int, leftBottom: Int, color: Int): ShapeDrawable {
            //左上、右上、右下、左下的圆角半径
            val radius = floatArrayOf(
                leftTop.toFloat(),
                leftTop.toFloat(),
                rightTop.toFloat(),
                rightTop.toFloat(),
                rightBottom.toFloat(),
                rightBottom.toFloat(),
                leftBottom.toFloat(),
                leftBottom.toFloat()
            )
            val drawable = ShapeDrawable().apply {
                shape = RoundRectShape(radius, null, null)
                paint.color = color
            }
            return drawable
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = inflate(layoutInflater)
        setContentView(mBinding.root)
        setOnDismissListener {
            NotifyMan.instance().unregister(mEventCallback)
        }
        init()
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        currEvent = event
        if (Lifecycle.Event.ON_DESTROY == event && isShowing) {
            dismiss()
        }
    }


    private fun getProperWidth(): Int {
        return Math.min(ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight())
    }

    fun init() {
        if (mActivity is ComponentActivity) {
            mActivity.lifecycle.addObserver(this)
        }
        setCanceledOnTouchOutside(true)
        window?.setBackgroundDrawableResource(R.color.transparent)
        width = (getProperWidth() * 0.8).toInt()
        height = WindowManager.LayoutParams.WRAP_CONTENT
        setWidthHeight()
        window?.setWindowAnimations(R.style.dialog_alpha)
    }

    fun with(): BindingDialog<VB> {
        create()
        setBg()
        return this
    }

    fun setAnimationsStyle(style: Int): BindingDialog<VB> {
        window?.setWindowAnimations(style)
        return this
    }

    /**
     * 设置位置
     */
    fun setGravity(gravity: Int, offX: Int, offY: Int): BindingDialog<VB> {
        setGravity(gravity)
        val layoutParams = window?.attributes
        layoutParams?.x = offX
        layoutParams?.y = offY
        window?.attributes = layoutParams
        return this
    }

    fun setGravity(gravity: Int): BindingDialog<VB> {
        window?.setGravity(gravity)
        return this
    }


    fun setBottom(): BindingDialog<VB> {
        setGravity(Gravity.BOTTOM)
        setAnimationsStyle(R.style.dialog_translate)
        setWidthRatio(1.0)
        setDBgRadius(24, 24, 0, 0)
        return this
    }

    fun setCanCancel(cancelable: Boolean = true): BindingDialog<VB> {
        setCanceledOnTouchOutside(cancelable)
        setCancelable(cancelable)
        return this
    }



    fun setCenter(cancelable: Boolean = true): BindingDialog<VB> {
        setGravity(Gravity.CENTER)
        setWidthRatio(0.8)
        setBgRadius(16)
        setAnimationsStyle(R.style.dialog_alpha)
        return this
    }

    override fun show() {
        if (!isShowing) {
            super.show()
        }
    }

    fun thisShow(): DialogInterface {
        this.show()
        return this
    }

    /**
     * 遮罩透明度
     *
     * @param value 0-1f
     */
    fun setMaskValue(value: Float): BindingDialog<VB> {
        window?.setDimAmount(value)
        return this
    }

    //    >>>>>>>>>>>>>>>>>>>>>>>>>>>>设置背景>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    open fun setBg(): BindingDialog<VB> {
        if (leftTopRadius != 0 || rightTopRadius != 0 || rightBottomRadius != 0 || leftBottomRadius != 0) {
            window?.setBackgroundDrawable(getRoundRectDrawable(leftTopRadius, rightTopRadius, rightBottomRadius, leftBottomRadius, bgColor))
        } else {
            window?.setBackgroundDrawable(getRoundRectDrawable(bgRadius, bgColor))
        }
        return this
    }

    /**
     * 设置背景颜色
     */
    fun setBgColor(@ColorInt color: Int): BindingDialog<VB> {
        bgColor = color
        return setBg()
    }

    fun setBgColorRes(colorRes: Int): BindingDialog<VB> {
        bgColor = ContextCompat.getColor(mActivity, colorRes)
        return setBg()
    }

    /**
     * 设置背景圆角
     */
    fun setBgRadius(bgRadius: Int): BindingDialog<VB> {
        this.bgRadius = bgRadius.dp
        return setBg()
    }

    /**
     * 设置背景不同圆角
     */
    fun setDBgRadius(leftTopRadius: Int, rightTopRadius: Int, rightBottomRadius: Int, leftBottomRadius: Int): BindingDialog<VB> {
        this.leftTopRadius = leftTopRadius.dp
        this.rightTopRadius = rightTopRadius.dp
        this.rightBottomRadius = rightBottomRadius.dp
        this.leftBottomRadius = leftBottomRadius.dp
        return setBg()
    }

    /**
     * 设置背景圆角
     */
    fun setBgRadiusPX(bgRadius: Int): BindingDialog<VB> {
        this.bgRadius = bgRadius
        return setBg()
    }

    //    >>>>>>>>>>>>>>>>>>>>>>>>>>>>设置宽高>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    /**
     * 设置宽高
     */
    open fun setWidthHeight(): BindingDialog<VB> {
        val dialogWindow = window
        val lp = dialogWindow?.attributes
        lp?.width = width
        lp?.height = height
        dialogWindow?.attributes = lp
        return this
    }

    fun setWidth(width: Int): BindingDialog<VB> {
        this.width = width.dp
        return setWidthHeight()
    }

    fun setWidthPX(width: Int): BindingDialog<VB> {
        this.width = width
        return setWidthHeight()
    }

    fun setHeight(height: Int): BindingDialog<VB> {
        this.height = height.dp
        return setWidthHeight()
    }

    fun setHeightPX(height: Int): BindingDialog<VB> {
        this.height = height
        return setWidthHeight()
    }

    /**
     * 设置宽占屏幕的比例
     */
    fun setWidthRatio(widthRatio: Double): BindingDialog<VB> {
        width = (getProperWidth() * widthRatio).toInt()
        setWidthHeight()
        return this
    }

    /**
     * 设置高占屏幕的比例
     */
    fun setHeightRatio(heightRatio: Double): BindingDialog<VB> {
        height = (ScreenUtils.getHeightRealPixels() * heightRatio).toInt()
        setWidthHeight()
        return this
    }

    //    >>>>>>>>>>>>>>>>>>>>>>>>>>>>设置监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    /**
     * 设置监听
     */
    open fun setOnClickListener(onClickListener: DialogOnClickListener, vararg viewIds: Int): BindingDialog<VB> {
        val lDialog: BindingDialog<VB> = this
        for (element in viewIds) {
            getView<View>(element).setOnClickListener { v -> onClickListener.onClick(v, lDialog) }
        }
        return this
    }

    interface DialogOnClickListener {
        fun onClick(v: View, lDialog: BindingDialog<*>)
    }

    /**
     * 设置 关闭dialog的按钮
     */
    fun setCancelBtn(viewId: Int): BindingDialog<VB> {
        getView<View>(viewId)?.setOnClickListener(View.OnClickListener { dismiss() })
        return this
    }

    //    >>>>>>>>>>>>>>>>>>>>>>>>>>>>设置常见属性>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    @Suppress("UNCHECKED_CAST")
    fun <T : View> getView(@IdRes viewId: Int): T {
        var view = views[viewId]
        if (view == null) {
            view = mBinding.root.findViewById<T>(viewId)
            views[viewId] = view
        }
        return view as T
    }

    /**
     * Will set the text of a TextView.
     *
     * @param viewId The view id.
     * @param value  The text to put in the text view.
     * @return The BaseViewHolder for chaining.
     */
    fun setText(@IdRes viewId: Int, value: CharSequence): BindingDialog<VB> {
        val view = getView<TextView>(viewId)
        view.text = value
        return this
    }

    fun setText(@IdRes viewId: Int, @StringRes strId: Int): BindingDialog<VB> {
        val view = getView<TextView>(viewId)
        view.setText(strId)
        return this
    }

    /**
     * Will set the image of an ImageView from a resource id.
     *
     * @param viewId     The view id.
     * @param imageResId The image resource id.
     * @return The BaseViewHolder for chaining.
     */
    fun setImageResource(@IdRes viewId: Int, @DrawableRes imageResId: Int): BindingDialog<VB> {
        val view = getView<ImageView>(viewId)
        view.setImageResource(imageResId)
        return this
    }

    /**
     * Will set background color of a view.
     *
     * @param viewId The view id.
     * @param color  A color, not a resource id.
     * @return The BaseViewHolder for chaining.
     */
    fun setBackgroundColor(@IdRes viewId: Int, @ColorInt color: Int): BindingDialog<VB> {
        val view = getView<View>(viewId)
        view.setBackgroundColor(color)
        return this
    }

    /**
     * Will set background of a view.
     *
     * @param viewId        The view id.
     * @param backgroundRes A resource to use as a background.
     * @return The BaseViewHolder for chaining.
     */
    fun setBackgroundRes(@IdRes viewId: Int, @DrawableRes backgroundRes: Int): BindingDialog<VB> {
        val view = getView<View>(viewId)
        view.setBackgroundResource(backgroundRes)
        return this
    }

    /**
     * Will set text color of a TextView.
     *
     * @param viewId    The view id.
     * @param textColor The text color (not a resource id).
     * @return The BaseViewHolder for chaining.
     */
    fun setTextColor(@IdRes viewId: Int, @ColorInt textColor: Int): BindingDialog<VB> {
        val view = getView<TextView>(viewId)
        view.setTextColor(textColor)
        return this
    }


    /**
     * Will set the image of an ImageView from a drawable.
     *
     * @param viewId   The view id.
     * @param drawable The image drawable.
     * @return The BaseViewHolder for chaining.
     */
    fun setImageDrawable(@IdRes viewId: Int, drawable: Drawable): BindingDialog<VB> {
        val view = getView<ImageView>(viewId)
        view.setImageDrawable(drawable)
        return this
    }

    /**
     * Add an action to set the image of an image view. Can be called multiple times.
     */
    fun setImageBitmap(@IdRes viewId: Int, bitmap: Bitmap): BindingDialog<VB> {
        val view = getView<ImageView>(viewId)
        view.setImageBitmap(bitmap)
        return this
    }

    /**
     * Add an action to set the alpha of a view. Can be called multiple times.
     * Alpha between 0-1.
     */
    fun setAlpha(@IdRes viewId: Int, value: Float): BindingDialog<VB> {
        getView<View>(viewId).alpha = value
        return this
    }

    /**
     * Set a view visibility to VISIBLE (true) or GONE (false).
     *
     * @param viewId  The view id.
     * @param visible True for VISIBLE, false for GONE.
     * @return The BaseViewHolder for chaining.
     */
    fun setGone(@IdRes viewId: Int, visible: Boolean): BindingDialog<VB> {
        val view = getView<View>(viewId)
        view.visibility = if (visible) View.VISIBLE else View.GONE
        return this
    }

    /**
     * Set a view visibility to VISIBLE (true) or INVISIBLE (false).
     *
     * @param viewId  The view id.
     * @param visible True for VISIBLE, false for INVISIBLE.
     * @return The BaseViewHolder for chaining.
     */
    fun setVisible(@IdRes viewId: Int, visible: Boolean): BindingDialog<VB> {
        val view = getView<View>(viewId)
        view.visibility = if (visible) View.VISIBLE else View.INVISIBLE
        return this
    }

}