package com.convenient.android.common.utils

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.widget.Toast

/**
 *    @author : hubowen
 *    @date   : 2020/9/18  3:24 PM
 *    @description：
 */
class ToastUtil constructor() {
    companion object {
        private var mToast: Toast? = null
        private var mHandler: Handler? = null
        private val mainThreadHandler: Handler?
            get() {
                if (mHandler == null) {
                    synchronized(ToastUtil::class.java) {
                        if (mHandler == null) mHandler = Handler(Looper.getMainLooper())
                    }
                }
                return mHandler
            }

        fun showToast(mContext: Context?, text: String?, duration: Int) {
            mToast?.cancel()
            mainThreadHandler?.post {
                mToast = Toast.makeText(mContext, text, duration)
                mToast?.show()
            }
        }

        @JvmStatic
        fun showToast(mContext: Context?, text: String?) {
            if (mContext != null) showToast(mContext, text, Toast.LENGTH_SHORT)
        }

        @JvmStatic
        fun showToast(mContext: Context?, resourceId: Int) {
            if (mContext != null) showToast(mContext, mContext.resources.getString(resourceId), Toast.LENGTH_SHORT)
        }

        @JvmStatic
        fun showLongToast(mContext: Context?, resourceId: Int) {
            if (mContext != null) showToast(mContext, mContext.resources.getString(resourceId), Toast.LENGTH_LONG)
        }

        @JvmStatic
        fun showLongToast(mContext: Context?, msg: String?) {
            if (mContext != null) showToast(mContext, msg, Toast.LENGTH_LONG)
        }

        @JvmStatic
        fun showToast(mContext: Context?, resourceId: Int, duration: Int) {
            if (mContext != null) showToast(mContext, mContext.resources.getString(resourceId), duration)
        }

    }

    init {
        /* cannot be instantiated */
        throw UnsupportedOperationException("cannot be instantiated")
    }
}