package com.remax.visualnovel.manager


import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.widget.Toast
import java.lang.ref.SoftReference

/**
 * Created by HJW on 2021/1/7
 */
object CustomToastManager {
    private var toastReference: SoftReference<Toast>? = null

    private var isShowingToast = false

    class MyHandler : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                0 -> {
                    isShowingToast = false
                }
            }
        }
    }

    private lateinit var handler: MyHandler

    fun showToast(context: Context, content: String?, isLong: Boolean = false) {
        if (content.isNullOrBlank()) return
        if (toastReference == null || toastReference?.get() == null) {
            val toast = createToast(context, content)
            toastReference = SoftReference(toast)
        }
        toastReference?.get()?.let {
            if (!isShowingToast) {
                isShowingToast = true
                it.setText(content)
                it.duration = if (isLong) Toast.LENGTH_LONG else Toast.LENGTH_SHORT
                it.show()
                val time = 1000L * 2
                if (this::handler.isInitialized) {
                    handler.sendEmptyMessageDelayed(0, time)
                } else {
                    handler = MyHandler()
                    handler.sendEmptyMessageDelayed(0, time)
                }
            } else {
                it.setText(content)
            }
        }
    }

    fun hideToast() {
        toastReference?.get()?.cancel()
    }

    private fun createToast(context: Context, content: String): Toast {
        handler = MyHandler()
        return Toast.makeText(context, content, Toast.LENGTH_SHORT)
    }


}