package com.adealink.weparty.commonui.imageview

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Animatable
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.webkit.URLUtil
import android.widget.FrameLayout
import com.adealink.frame.base.fastLazy
import com.adealink.frame.image.view.NetworkImageView
import com.adealink.frame.image.view.NetworkImageView.IImageLoadResultListener
import com.adealink.frame.image.view.zoomable.IExtraListener
import com.adealink.frame.image.view.zoomable.ZoomableDraweeView
import com.adealink.frame.util.ImageUtil
import com.adealink.weparty.commonui.ext.isGIFImage
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.controller.BaseControllerListener
import com.facebook.drawee.drawable.ProgressBarDrawable
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder
import com.facebook.drawee.interfaces.DraweeController
import com.facebook.imagepipeline.image.ImageInfo

/**
 * 结合DarweeView与NetworkImageView
 */
class FusionPreviewImageView : FrameLayout {

    private var netWorkImageView: NetworkImageView? = null
    private var zoomableDrawView: ZoomableDraweeView? = null
    var extraListener: IExtraListener? = null
    private var imageLoadedSuccess = false

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    //用于GIF图长按和下滑检测
    private val gestureDetector by fastLazy {
        GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
            private val SWIPE_THRESHOLD = 100
            private val SWIPE_VELOCITY_THRESHOLD = 100

            override fun onFling(
                e1: MotionEvent?,
                e2: MotionEvent,
                velocityX: Float,
                velocityY: Float
            ): Boolean {
                if (e1 == null) return false
                val deltaY = e2.y - e1.y
                if (deltaY > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    extraListener?.onSwipeDown()
                    return true
                }
                return false
            }

            override fun onLongPress(e: MotionEvent) {
                super.onLongPress(e)
                if (!imageLoadedSuccess) {
                    return
                }
                extraListener?.onLongClick()
            }
        })
    }

    @SuppressLint("ClickableViewAccessibility")
    fun setImagePath(urlPath: String) {
        removeAllViews()
        if (isGIFImage(urlPath)) {
            getNetworkImageView()?.let {
                it.setImageUrl(
                    if (URLUtil.isNetworkUrl(urlPath)) {
                        urlPath
                    } else if (urlPath.startsWith("content:") || urlPath.startsWith("file:")) {
                        urlPath
                    } else {
                        ImageUtil.getImageUri(urlPath)?.toString()
                    },
                    object : IImageLoadResultListener {
                        override fun onFailed() {
                            imageLoadedSuccess = false
                        }

                        override fun onSuccess(imageInfo: ImageInfo?) {
                            imageLoadedSuccess = true
                        }
                    }
                )
                it.setOnLongClickListener {
                    if (!imageLoadedSuccess) {
                        return@setOnLongClickListener false
                    }
                    extraListener?.onLongClick()
                    true
                }
                it.setOnTouchListener { _, event ->
                    // 将触摸事件交给 GestureDetector 处理
                    gestureDetector.onTouchEvent(event)
                    true
                }

                addView(it)
            }
        } else {
            getZoomableDraweeView()?.let {
                val ctrl: DraweeController = Fresco.newDraweeControllerBuilder()
                    .setUri(
                        if (URLUtil.isNetworkUrl(urlPath)) {
                            urlPath
                        } else if (urlPath.startsWith("content:") || urlPath.startsWith("file:")){
                            urlPath
                        } else {
                            ImageUtil.getImageUri(urlPath)?.toString()
                        }
                    ).setTapToRetryEnabled(true)
                    .setControllerListener(
                        object : BaseControllerListener<ImageInfo>() {
                            override fun onFinalImageSet(
                                id: String?,
                                imageInfo: ImageInfo?,
                                animatable: Animatable?
                            ) {
                                super.onFinalImageSet(id, imageInfo, animatable)
                                imageLoadedSuccess = true
                            }

                            override fun onFailure(id: String?, throwable: Throwable?) {
                                super.onFailure(id, throwable)
                                imageLoadedSuccess = false
                            }
                        }
                    )
                    .build()
                it.setExtraListener(object : IExtraListener {
                    override fun onLongClick() {
                        extraListener?.onLongClick()
                    }

                    override fun onSwipeDown() {
                        extraListener?.onSwipeDown()
                    }

                })
                it.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
                val hierarchy = GenericDraweeHierarchyBuilder(resources)
                    .setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER)
                    .setProgressBarImage(ProgressBarDrawable())
                    .build()
                it.controller = ctrl
                it.hierarchy = hierarchy
                addView(it)
            }
        }
    }

    private fun getNetworkImageView(): NetworkImageView? {
        if (netWorkImageView == null) {
            netWorkImageView = NetworkImageView(context)
            netWorkImageView?.layoutParams =
                LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
            netWorkImageView?.hierarchy = GenericDraweeHierarchyBuilder(resources)
                .setActualImageScaleType(ScalingUtils.ScaleType.CENTER_INSIDE)
                .build()
        }
        return netWorkImageView
    }

    private fun getZoomableDraweeView(): ZoomableDraweeView? {
        if (zoomableDrawView == null) {
            zoomableDrawView = ZoomableDraweeView(context)
        }
        return zoomableDrawView
    }


}