package cn.yyxx.eyuangame.core.ui.dialog

import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.text.TextUtils
import android.view.*
import android.widget.LinearLayout
import android.widget.TextView
import cn.yyxx.support.DensityUtils
import cn.yyxx.support.ui.scaleprogress.ScaleLoadingView

/**
 * @author #Suyghur.
 * Created on 2021/07/01
 */
class ScaleLoadingDialog constructor(context: Context, desc: String) : Dialog(context), DialogInterface.OnKeyListener {

    private lateinit var layout: LinearLayout

    private var loadingView: ScaleLoadingView? = null

    init {
        setCanceledOnTouchOutside(false)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        initView(context, desc)
    }

    private fun initView(context: Context, desc: String) {
        val attr = window?.attributes as WindowManager.LayoutParams
        //设置dialog在布局中的位置
        attr.gravity = Gravity.CENTER

        val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        layout = LinearLayout(context)
        layout.orientation = LinearLayout.VERTICAL

        val viewSize = DensityUtils.dip2px(context, 60f)
        val divideSize = DensityUtils.dip2px(context, 3f)
        val count = 5
        val startColor = Color.parseColor("#7EB944")
        val endColor = Color.parseColor("#1DB1AD")
        loadingView = ScaleLoadingView(context, viewSize, divideSize, count, startColor, endColor)
        val loadingViewParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        loadingViewParams.gravity = Gravity.CENTER
        layout.addView(loadingView, loadingViewParams)

        if (!TextUtils.isEmpty(desc)) {
            val textView = TextView(context)
            textView.text = desc
            textView.setTextColor(Color.WHITE)
            val textViewParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
            textViewParams.gravity = Gravity.CENTER
            layout.addView(textView, textViewParams)
        }

        addContentView(layout, params)
        setOnKeyListener(this)
    }

    override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent): Boolean {
        return keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0
    }
}