package com.remax.visualnovel.widget.imageviewer.viewer

import android.widget.ImageView
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.remax.visualnovel.extension.findActivityContext
import com.remax.visualnovel.widget.imageviewer.core.Transformer
import dagger.hilt.android.internal.ThreadUtil
import timber.log.Timber

class SimpleTransformer : Transformer {
    override fun getView(key: Long): ImageView? = ViewerTransitionHelper.provide(key)
}

/**
 * 维护Transition过渡动画的缩略图和大图之间的映射关系.
 */
object ViewerTransitionHelper {

    private val transition = HashMap<ImageView, Long>()

    fun put(imageView: ImageView?, photoId: Long = imageView.hashCode().toLong()) {
        require(ThreadUtil.isMainThread())
        (imageView?.context?.findActivityContext() as? LifecycleOwner)?.lifecycle?.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                transition.remove(imageView)
                Timber.d("transitionHashMap onLifecycleObserverDestroy remove :${transition.size}")
            }
        })
        imageView?.let {
            transition[imageView] = photoId
            Timber.d("transitionHashMap put :${transition.size}")
        }
    }

    fun provide(photoId: Long): ImageView? {
        transition.keys.forEach {
            if (transition[it] == photoId)
                return it
        }
        return null
    }
}