package com.gh.gamecenter.common.base

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.KeyEvent
import com.gh.gamecenter.core.utils.MtaHelper
import java.util.concurrent.atomic.AtomicBoolean

open class TrackableDialog(
    context: Context,
    themeResId: Int,
    private var mEvent: String,
    private var mKey: String,
    private var mValue: String? = null,
    private var mCancelValue: String? = null,
    private var mKeyBackValue: String? = null,
    private var mLogShowEvent: Boolean = true
) : Dialog(context, themeResId) {

    // 区分此 dialog 是点击 dialog 外部取消的还是点击返回取消的
    private val mIsCanceledByClickOutsideOfDialog = AtomicBoolean(true)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setOnCancelListener {
            if (mIsCanceledByClickOutsideOfDialog.get()) {
                MtaHelper.onEvent(mEvent, mKey, mCancelValue ?: "点击空白")
                if (!mValue.isNullOrEmpty()) {
                    MtaHelper.onEvent(mEvent, "点击空白", mValue)
                }
            }
        }

        setOnKeyListener { _, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP) {
                mIsCanceledByClickOutsideOfDialog.set(false)
                MtaHelper.onEvent(mEvent, mKey, mKeyBackValue ?: "点击返回")
                if (mValue != null) {
                    MtaHelper.onEvent(mEvent, "点击返回", mValue)
                }
            }
            false
        }
    }

    override fun show() {
        super.show()
        if (mLogShowEvent) {
            MtaHelper.onEvent(mEvent, mKey, "出现弹窗")
            if (!mValue.isNullOrEmpty()) {
                MtaHelper.onEvent(mEvent, "出现弹窗", mValue)
            }
        }
    }

}