package com.gh.gamecenter.common.view

import android.text.Selection
import android.text.Spannable
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.URLSpan
import android.view.MotionEvent
import android.view.ViewGroup
import android.view.ViewParent
import android.widget.TextView
import com.therouter.TheRouter
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.core.provider.IDefaultUrlHandlerProvider

/**
 * 拦截处理以 "ghzhushou://" 起始的 URLSpan
 */
class UrlInterceptedLinkMovementMethod : LinkMovementMethod() {

    override fun onTouchEvent(widget: TextView, buffer: Spannable, event: MotionEvent): Boolean {
        val action = event.action
        var isTouchEventConsumed = false
        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
            var x = event.x.toInt()
            var y = event.y.toInt()
            x -= widget.totalPaddingLeft
            y -= widget.totalPaddingTop
            x += widget.scrollX
            y += widget.scrollY
            val layout = widget.layout
            val line = layout.getLineForVertical(y)
            val off = layout.getOffsetForHorizontal(line, x.toFloat())
            val links = buffer.getSpans(off, off, ClickableSpan::class.java)
            if (links.size != 0) {
                val link = links[0]
                if (action == MotionEvent.ACTION_UP) {
                    if (link is URLSpan && link.url.contains("ghzhushou")) {
                        val provider = TheRouter.get(IDefaultUrlHandlerProvider::class.java)
                        provider?.interceptUrl(widget.context, link.url, "")
                    } else {
                        link.onClick(widget)
                    }
                } else if (action == MotionEvent.ACTION_DOWN) {
                    // do nothing
                }
                isTouchEventConsumed = true
            } else {
                Selection.removeSelection(buffer)
            }
        }

        //解决点击事件冲突问题
        if (!isTouchEventConsumed && event.action == MotionEvent.ACTION_UP) {
            val parent: ViewParent? = iterateViewParentForClicking(widget.parent) //处理widget的父控件点击事件
            if (parent is ViewGroup) {
                return parent.performClick()
            }
        }
        return false
    }

    private fun iterateViewParentForClicking(parent: ViewParent): ViewParent? {
        return if (parent is ViewGroup) {
            if (parent.hasOnClickListeners()) {
                parent
            } else {
                iterateViewParentForClicking(parent.getParent())
            }
        } else null
    }

}