package com.seatel.mobilehall.util.customview

import android.app.Activity
import android.content.Context
import android.graphics.Typeface
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatButton
import com.seatel.mobilehall.util.FontCache
import com.seatel.mobilehall.util.lang.LanguageManager

class CustomButton @JvmOverloads constructor(
    context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatButton(context!!, attrs, defStyleAttr) {


    val ANDROID_SCHEMA = "http://schemas.android.com/apk/res/android"
    var noTranslate = false


    init {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?) {
        if (!isInEditMode) {
            var textStyle = Typeface.NORMAL
            if (attrs != null)
                textStyle = attrs.getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL)
            val customFont = FontCache.getFont(context, textStyle)
            val plain = FontCache[context, customFont]
            this@CustomButton.setTypeface(plain, super.getTypeface().style)

        }
    }

    override fun setText(text: CharSequence?, type: BufferType?) {

        if (text != null && !isInEditMode) {
            (context as Activity).runOnUiThread(object : Runnable {
                override fun run() {
                    if (noTranslate)
                        super@CustomButton.setText(text.toString(), type)
                    else
                        super@CustomButton.setText(
                            LanguageManager(context).translateWords(
                                context, text.toString()
                            ), type
                        )
                    super@CustomButton.setAllCaps(false)
                    removeCallbacks(this)
                }
            })
        } else {
            super.setText(text, type)
        }


    }


}