package com.seatel.mobilehall.util.customview

import android.content.Context
import android.graphics.Typeface
import android.text.TextUtils
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.seatel.mobilehall.util.FontCache
import com.seatel.mobilehall.util.FontCache.getFont
import com.seatel.mobilehall.util.lang.LanguageManager

class CustomTextView : AppCompatTextView {

    constructor(context: Context) : super(context) {
        noTranslate = false
        applyCustomFont(context, null)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        noTranslate = false
        applyCustomFont(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        noTranslate = false
        applyCustomFont(context, attrs)
    }

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

    override fun setText(text: CharSequence, type: BufferType) {
        if (!TextUtils.isEmpty(text) && !isInEditMode) {
            if (noTranslate) super@CustomTextView.setText(
                text.toString().replace("\\n", "\r\n"),
                type
            ) else super@CustomTextView.setText(
                LanguageManager(
                    context
                ).translateWords(context, text.toString()).replace("\\n", "\r\n"), type
            )
        } else {
            super.setText(text, type)
        }
    }

    companion object {
        const val ANDROID_SCHEMA = "http://schemas.android.com/apk/res/android"
        var noTranslate = false
    }
}