package com.yidian.bcommon.widget

import android.content.Context
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.yidian.bcommon.R

/**
 * 数据加载的loading
 */
class LoadingDialog(context: Context) : AlertDialog(context, R.style.Theme_AppCompat_Dialog) {

  constructor(context: Context, cancelable: Boolean) : this(context) {
    this.setCancelable(cancelable)
  }

  private val tvMessage: TextView
  private var mStartTime: Long = -1
  private var mPostedHide = false
  private var mPostedShow = false
  private var mDismissed = false
  private val mHandler: Handler = Handler()

  private val mDelayedHide = Runnable {
    mPostedHide = false
    mStartTime = -1
    dismiss()
  }

  private val mDelayedShow = Runnable {
    mPostedShow = false
    if (!mDismissed) {
      mStartTime = System.currentTimeMillis()
      show()
    }
  }

  /**
   * 显示loading
   */
  fun showDialog(message: String?) {
    tvMessage.text = message
    mStartTime = -1
    mDismissed = false
    mHandler.removeCallbacks(mDelayedHide)
    mPostedHide = false
    if (!mPostedShow) {
      mHandler.postDelayed(mDelayedShow, MIN_DELAY)
      mPostedShow = true
    }
  }

  /**
   * 隐藏loading
   */
  fun hideDialog() {
    mDismissed = true
    mHandler.removeCallbacks(mDelayedShow)
    mPostedShow = false
    val diff = System.currentTimeMillis() - mStartTime
    if (diff >= MIN_SHOW_TIME || mStartTime == -1L) {
      dismiss()
    } else {
      if (!mPostedHide) {
        mHandler.postDelayed(mDelayedHide, MIN_SHOW_TIME - diff)
        mPostedHide = true
      }
    }
  }

  override fun onDetachedFromWindow() {
    super.onDetachedFromWindow()
    mHandler.removeCallbacks(mDelayedHide)
    mHandler.removeCallbacks(mDelayedShow)
  }

  companion object {
    private const val MIN_SHOW_TIME = 500
    private const val MIN_DELAY = 500L
  }

  init {
    val loadView: View = LayoutInflater.from(getContext()).inflate(R.layout.dialog_loading, null)
    setView(loadView)
    tvMessage = loadView.findViewById(R.id.tv_message)
  }
}
