package com.gh.gamecenter.common.view

import android.content.Context
import android.graphics.drawable.Animatable
import android.util.AttributeSet
import androidx.annotation.Nullable
import com.facebook.drawee.backends.pipeline.PipelineDraweeController
import com.facebook.drawee.controller.BaseControllerListener
import com.facebook.drawee.interfaces.DraweeController
import com.facebook.drawee.view.SimpleDraweeView
import com.facebook.imagepipeline.image.ImageInfo

class WrapContentDraweeView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : SimpleDraweeView(context, attrs, defStyleAttr) {

    var loadingCallback: LoadingCallback? = null

    // we set a listener and update the view's aspect ratio depending on the loaded image
    private val listener = object : BaseControllerListener<ImageInfo>() {
        override fun onIntermediateImageSet(id: String?, @Nullable imageInfo: ImageInfo?) {
            updateViewSize(imageInfo)
            loadingCallback?.loaded()
        }

        override fun onFinalImageSet(id: String?, @Nullable imageInfo: ImageInfo?, @Nullable animatable: Animatable?) {
            updateViewSize(imageInfo)
            loadingCallback?.loaded()
        }

        override fun onFailure(id: String?, throwable: Throwable?) {
            loadingCallback?.loaded()
        }
    }

    override fun setController(draweeController: DraweeController?) {
        if (draweeController is PipelineDraweeController) {
            draweeController.addControllerListener(listener)
        }
        super.setController(draweeController)
    }

    internal fun updateViewSize(@Nullable imageInfo: ImageInfo?) {
        if (imageInfo != null) {
            aspectRatio = imageInfo.width.toFloat() / imageInfo.height
        }
    }

    interface LoadingCallback {
        fun loaded()
    }
}