package com.lukouguoji.module_base.impl

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import java.util.concurrent.ConcurrentHashMap

/**
 * @author：孟凡华
 * @date：2022/12/1
 * @desc：
 */
object FlowBus {

    // 总线map
    private val busMap = ConcurrentHashMap<Any, MutableSharedFlow<Any>>()

    // 粘性事件总线map
    private val busStickyMap = ConcurrentHashMap<Any, MutableSharedFlow<Any>>()

    /**
     * 根据Key获取事件总线
     */
    fun <T> with(key: String): MutableSharedFlow<T> {
        if (!busMap.containsKey(key)) {
            busMap[key] = MutableSharedFlow(0, 1, BufferOverflow.DROP_OLDEST)
        }
        return busMap[key] as MutableSharedFlow<T>
    }

    /**
     * 根据Key获取事件总线
     * 粘性事件需要发送及接收都使用才奏效
     */
    fun <T> withSticky(key: String): MutableSharedFlow<T> {
        if (!busStickyMap.containsKey(key)) {
            busStickyMap[key] = MutableSharedFlow(1, 1, BufferOverflow.DROP_OLDEST)
        }
        return busStickyMap[key] as MutableSharedFlow<T>
    }

}

/**
 * 观察事件
 * 自动释放,根据生命周期自动释放资源
 */
fun <T> MutableSharedFlow<T>.observe(
    lifecycleOwner: LifecycleOwner,
    action: (T) -> Unit
) {
    // 接收事件
    lifecycleOwner.lifecycleScope.launch {
        collect { action(it) }
    }
}

