package com.xty.common.weight

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.widget.TextView
import java.util.*


/**
 * Typer Effect
 * Created by hanks on 2017/3/15.
 */
@SuppressLint("AppCompatCustomView")
class TyperTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : TextView(context, attrs) {
    private val MSG_WHAT = 0x767
    private val random: Random
    private var mText: CharSequence
    private var charIncrease: Int = 0
    private var typerSpeed: Int = 0
    private var animationListener: AnimationListener? = null
    private lateinit var mHandler: Handler

    init {
        typerSpeed = 200
        charIncrease = 1

        random = Random()
        mText = text

        mHandler = Handler(Looper.getMainLooper()) {
            val currentLength: Int = text.length
            if (currentLength < mText.length) {
                if (currentLength + charIncrease > mText.length) {
                    charIncrease = mText.length - currentLength
                }
                append(mText.subSequence(currentLength, currentLength + charIncrease))
                val randomTime = (typerSpeed + random.nextInt(typerSpeed)).toLong()
                val message = Message.obtain()
                message.what = MSG_WHAT
                mHandler.sendMessageDelayed(message, randomTime)
                false
            } else {
                //如果没有设置动画监听，则一直动画
                if (null == animationListener) {
                    text = ""
                    val message = Message.obtain()
                    message.what = MSG_WHAT
                    mHandler.sendMessage(message)
                } else {
                    animationListener?.onAnimationEnd(this@TyperTextView)
                }

            }
            false
        }
    }


    fun setAnimationListener(listener: AnimationListener?) {
        animationListener = listener
    }

    fun setProgress(progress: Float) {
        text = mText.subSequence(0, (mText.length * progress).toInt())
    }

    fun animateText(text: CharSequence?) {
        if (text == null) {
            throw RuntimeException("text must not  be null")
        }
        mText = text
        setText("")
        val message = Message.obtain()
        message.what = MSG_WHAT
        mHandler.sendMessage(message)
    }

    fun cancelAnimate(){
        mHandler.removeMessages(MSG_WHAT)
        animationListener?.onAnimationEnd(this@TyperTextView)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        mHandler.removeMessages(MSG_WHAT)
    }


    /**
     * AnimationListener
     */
    interface AnimationListener {
        fun onAnimationEnd(typerTextView: TyperTextView?)
    }
}
