package com.ydl.ydlcommon.mvp.presenter

import androidx.collection.ArrayMap
import com.ydl.ydlcommon.mvp.base.IPresenter
import com.ydl.ydlcommon.mvp.base.IView

/**
 * Created by haorui on 2019-08-14.
 * Des: Activity Presenter 缓存类
 *      适应单Activity多Presenter情况
 */
internal class ActivityPresenterCache {

    private val presenterMap =
        ArrayMap<String, PresenterHolder>()

    fun clear() {
        presenterMap.clear()
    }

    fun <P> getPresenter(viewId: String): P? {
        val holder = presenterMap[viewId]
        return if (holder == null) null else holder.presenter as P?
    }

    fun putPresenter(
        viewId: String,
        presenter: IPresenter<out IView>
    ) {

        var presenterHolder = presenterMap[viewId]
        if (presenterHolder == null) {
            presenterHolder = PresenterHolder()
            presenterHolder.presenter = presenter
            presenterMap[viewId] = presenterHolder
        } else {
            presenterHolder.presenter = presenter
        }
    }


    fun remove(viewId: String) {

        presenterMap.remove(viewId)
    }


    internal class PresenterHolder {
        var presenter: IPresenter<*>? = null
    }
}
