package com.cooleshow.base.widgets

import android.app.Dialog
import android.content.Context
import android.graphics.drawable.AnimationDrawable
import android.view.Gravity
import android.widget.ImageView
import android.widget.TextView
import com.cooleshow.base.R
import com.cooleshow.base.utils.LogUtils
import com.cooleshow.base.utils.UiUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 上传进度条
 */
class UploadProgressLoading private constructor(context: Context, theme: Int) :
    Dialog(context, theme) {

    companion object {
        private lateinit var mDialog: UploadProgressLoading
        private var animDrawable: AnimationDrawable? = null
        private var tvProgress: TextView? = null;

        /*
            创建加载对话框
         */
        fun create(context: Context): UploadProgressLoading {
            LogUtils.i("pq","thread:"+Thread.currentThread().name);
            //样式引入
            mDialog = UploadProgressLoading(context, R.style.LightProgressDialog)
            //设置布局
            mDialog.setContentView(R.layout.upload_progress_dialog)
            mDialog.setCancelable(false)
            mDialog.setCanceledOnTouchOutside(false)
            mDialog.window?.attributes?.gravity = Gravity.CENTER

            val lp = mDialog.window?.attributes
            lp?.dimAmount = 0.2f
            //设置属性
            mDialog.window?.attributes = lp

            //获取动画视图
            val loadingView = mDialog.findViewById<ImageView>(R.id.iv_loading)

            tvProgress = mDialog.findViewById<TextView>(R.id.tv_progress)

            animDrawable = loadingView.background as AnimationDrawable

            return mDialog
        }
    }

    fun setProgress(progress: Double) {
        GlobalScope.launch(Dispatchers.Main) {
            tvProgress?.let {
                var result: String = UiUtils.convertDouble(progress);
                tvProgress?.text = "$result%"
            }
        }
    }

    /*
        显示加载对话框，动画开始
     */
    fun showLoading() {
        GlobalScope.launch(Dispatchers.Main) {
            super.show()
            animDrawable?.start()
        }
    }

    /*
        隐藏加载对话框，动画停止
     */
    fun hideLoading() {
        GlobalScope.launch(Dispatchers.Main) {
            super.dismiss()
            animDrawable?.stop()
        }
    }

    fun stopAnim() {
        animDrawable?.stop()
    }
}
