package com.remax.visualnovel.widget.uitoken.view

import android.content.Context
import android.graphics.Paint
import android.text.Selection
import android.text.Spannable
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import androidx.appcompat.widget.AppCompatTextView
import com.remax.visualnovel.R
import com.remax.visualnovel.widget.uitoken.bean.CustomViewToken
import com.remax.visualnovel.widget.uitoken.changeBackground
import com.remax.visualnovel.widget.uitoken.changeOutline
import com.remax.visualnovel.widget.uitoken.changeTextColor
import com.remax.visualnovel.widget.uitoken.changeTextFont
import com.remax.visualnovel.widget.uitoken.expend.dsl.expand
import androidx.core.content.withStyledAttributes

/**
 * Created by HJW on 2022/8/31
 * 文字颜色暂时无法做到press enable等效果下渐变色
 *
 * ImageView, Layout, Edittext
 */
open class UITokenTextView @JvmOverloads constructor(context: Context, private val attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    AppCompatTextView(context, attrs, defStyleAttr), UIView {

    protected val customViewToken = CustomViewToken()
    var clickWithSelectableBlock: (() -> Unit)? = null

    init {
        includeFontPadding = false
        obtainStyledAttributes()
        changeStyle()
    }

    fun obtainStyledAttributes() {
        context.withStyledAttributes(attrs, R.styleable.UITokenTextView) {
            customViewToken.run {
                textUITextToken = getString(R.styleable.UITokenTextView_textToken).takeIf { it != null } ?: textUITextToken
                textUIColorToken = getString(R.styleable.UITokenTextView_textColorToken).takeIf { it != null } ?: textUIColorToken
                textUIPressedColorToken =
                    getString(R.styleable.UITokenTextView_textPressedColorToken).takeIf { it != null } ?: textUIPressedColorToken
                textUIHoveredColorToken =
                    getString(R.styleable.UITokenTextView_textHoveredColorToken).takeIf { it != null } ?: textUIHoveredColorToken
                textUIDisabledColorToken =
                    getString(R.styleable.UITokenTextView_textDisabledColorToken).takeIf { it != null } ?: textUIDisabledColorToken
                textUIHintColorToken = getString(R.styleable.UITokenTextView_textHintColorToken).takeIf { it != null } ?: textUIHintColorToken
                textUILinkColorToken = getString(R.styleable.UITokenTextView_textLinkColorToken).takeIf { it != null } ?: textUILinkColorToken
                backgroundUIColorToken =
                    getString(R.styleable.UITokenTextView_backgroundColorToken).takeIf { it != null } ?: backgroundUIColorToken
                backgroundUIPressedColorToken =
                    getString(R.styleable.UITokenTextView_backgroundPressedColorToken).takeIf { it != null } ?: backgroundUIPressedColorToken
                backgroundUIHoveredColorToken =
                    getString(R.styleable.UITokenTextView_backgroundHoveredColorToken).takeIf { it != null } ?: backgroundUIHoveredColorToken
                backgroundUIDisabledColorToken =
                    getString(R.styleable.UITokenTextView_backgroundDisabledColorToken).takeIf { it != null } ?: backgroundUIDisabledColorToken
                radiusToken = getString(R.styleable.UITokenTextView_radiusToken).takeIf { it != null } ?: radiusToken
                topLeftRadiusToken = (getString(R.styleable.UITokenTextView_topLeftRadiusToken) ?: "").ifEmpty { radiusToken }
                topRightRadiusToken = (getString(R.styleable.UITokenTextView_topRightRadiusToken) ?: "").ifEmpty { radiusToken }
                bottomLeftRadiusToken = (getString(R.styleable.UITokenTextView_bottomLeftRadiusToken) ?: "").ifEmpty { radiusToken }
                bottomRightRadiusToken = (getString(R.styleable.UITokenTextView_bottomRightRadiusToken) ?: "").ifEmpty { radiusToken }
                strokeUIWidthToken = getString(R.styleable.UITokenTextView_strokeWidthToken).takeIf { it != null } ?: strokeUIWidthToken
                strokeUIColorToken = getString(R.styleable.UITokenTextView_strokeColorToken).takeIf { it != null } ?: strokeUIColorToken
                strokeUIPressedColorToken =
                    getString(R.styleable.UITokenTextView_strokePressedColorToken).takeIf { it != null } ?: strokeUIPressedColorToken
                strokeUIHoveredColorToken =
                    getString(R.styleable.UITokenTextView_strokeHoveredColorToken).takeIf { it != null } ?: strokeUIHoveredColorToken
                strokeUIDisabledColorToken =
                    getString(R.styleable.UITokenTextView_strokeDisabledColorToken).takeIf { it != null } ?: strokeUIDisabledColorToken
                outlineToken = getString(R.styleable.UITokenTextView_outlineToken).takeIf { it != null } ?: outlineToken
                xClickExpend = getDimensionPixelOffset(R.styleable.UITokenTextView_xClickExpend, xClickExpend)
                yClickExpend = getDimensionPixelOffset(R.styleable.UITokenTextView_yClickExpend, yClickExpend)
                strokeDashWidth = getDimensionPixelOffset(R.styleable.UITokenTextView_strokeDashWidth, 0).toFloat()
                strokeDashGap = getDimensionPixelOffset(R.styleable.UITokenTextView_strokeDashGap, 0).toFloat()
                onlyIconFont = getBoolean(R.styleable.UITokenTextView_onlyIconFont, onlyIconFont)
                underline = getBoolean(R.styleable.UITokenTextView_underline, underline)
                fixTextIsSelectable = getBoolean(R.styleable.UITokenTextView_fixTextIsSelectable, fixTextIsSelectable)


                //<!-- new added 2025.10.29 -->
                advBgColor = getColor(R.styleable.UITokenTextView_advBgColor, advBgColor)
                advRadius = getDimension(R.styleable.UITokenTextView_advRadius, advRadius)
                advTopLeftRadius = getDimension(R.styleable.UITokenTextView_advTopLeftRadius, advTopLeftRadius)
                advTopRightRadius = getDimension(R.styleable.UITokenTextView_advTopRightRadius, advTopRightRadius)
                advBottomRightRadius = getDimension(R.styleable.UITokenTextView_advBottomRightRadius, advBottomRightRadius)
                advBottomLeftRadius = getDimension(R.styleable.UITokenTextView_advBottomLeftRadius, advBottomLeftRadius)
                advStrokeColor = getColor(R.styleable.UITokenTextView_advStrokeColor, advStrokeColor)
                advStrokeWidth = getDimension(R.styleable.UITokenTextView_advStrokeWidth, advStrokeWidth)
            }

        }
    }

    /**
     * textView设置了isSelectable = true时
     * 解决android 8 TextView设置textIsSelectable="true" 报角标越界异常bug
     */
    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        if (customViewToken.fixTextIsSelectable) {
            val startSelection = selectionStart
            val endSelection = selectionEnd
            if (startSelection < 0 || endSelection < 0) {
                Selection.setSelection(text as Spannable, text.length)
            } else if (startSelection != endSelection) {
                if (event.actionMasked == MotionEvent.ACTION_DOWN) {
                    val text = text
                    setText(null)
                    setText(text)
                }
            }
        }
        return super.dispatchTouchEvent(event)
    }

    private var lastActionDownTime = -1L

    /**
     * TextView设置了长按复制、OnClickListener冲突的解决
     * @param event MotionEvent
     * @return Boolean
     */
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (isTextSelectable && clickWithSelectableBlock != null) {
            when (event?.action) {
                MotionEvent.ACTION_UP -> {
                    val actionUpTime = System.currentTimeMillis()
                    if (actionUpTime - lastActionDownTime <= ViewConfiguration.getLongPressTimeout()) {
                        /**
                         * 这里失焦一下
                         */
                        clickWithSelectableBlock?.invoke()
                        return true
                    }
                }

                MotionEvent.ACTION_DOWN -> {
                    lastActionDownTime = System.currentTimeMillis()
                }
            }
        }
        return super.onTouchEvent(event)
    }

    private fun changeStyle() {
        changeTextFont(customViewToken)
        changeTextColor(customViewToken)
        changeBackground(customViewToken)
        changeOutline(customViewToken)
        if (customViewToken.xClickExpend != 0 || customViewToken.yClickExpend != 0) {
            expand(customViewToken.xClickExpend, customViewToken.yClickExpend)
        }
        if (customViewToken.underline) {
            paint.flags = Paint.UNDERLINE_TEXT_FLAG
            paint.isAntiAlias = true
        }
    }

    override fun getUITokenView(): CustomViewToken {
        return customViewToken
    }
}
