package com.adealink.weparty.commonui.widget

import android.content.Context
import android.graphics.Rect
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatTextView
import com.adealink.frame.util.DisplayUtil

class MarqueeTextView : AppCompatTextView {

    private val isLeft: Boolean = !DisplayUtil.isRtlLayout()

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
        isFocusable = true
        isFocusableInTouchMode = true
        ellipsize = TextUtils.TruncateAt.MARQUEE
        marqueeRepeatLimit = -1
        setSingleLine()
    }

    private var marqueeEnable: Boolean = true

    fun setMarqueeEnable(enable: Boolean) {
        marqueeEnable = enable
    }

    fun setMarqueeEnable(enable: Boolean, ellipsizeWhenDisable: TextUtils.TruncateAt) {
        if (enable) {
            marqueeEnable = true
            ellipsize = TextUtils.TruncateAt.MARQUEE
        } else {
            marqueeEnable = false
            ellipsize = ellipsizeWhenDisable
        }
    }

    override fun isFocused(): Boolean {
        return marqueeEnable
    }

    override fun onFocusChanged(
        focused: Boolean, direction: Int,
        previouslyFocusedRect: Rect?
    ) {
        if (focused) {
            super.onFocusChanged(focused, direction, previouslyFocusedRect)
        }
    }

    override fun getLayoutDirection(): Int {
        return if (isLeft) View.LAYOUT_DIRECTION_LTR else View.LAYOUT_DIRECTION_RTL
    }

    override fun getTextDirection(): Int {
        return if (isLeft) View.TEXT_DIRECTION_LTR else View.TEXT_DIRECTION_RTL
    }

    override fun onWindowFocusChanged(focused: Boolean) {
        if (focused) {
            super.onWindowFocusChanged(focused)
        }
    }
}
