package com.remax.visualnovel.app.initializer

import android.app.Application
import android.util.Log
import com.remax.visualnovel.app.initializer.di.AppInitializerEntryPoint
import dagger.hilt.android.EntryPointAccessors
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * Created by HJW on 2023/5/11
 */
class AppInitializersProvider @Inject constructor(private val application: Application) {

    private val TAG = "AppInitializersProvider"

    private val initializers: Set<AppInitializers> by lazy {
        EntryPointAccessors.fromApplication(application, AppInitializerEntryPoint::class.java)
            .getAppInitializers()
    }

    fun startInit() {
        val seriesList = initializers.filter {
            it.getStartType() == AppInitializerStartType.TYPE_SERIES
        }.sortedByDescending { it.widget() }
        val parallelList =
            initializers.filter { it.getStartType() == AppInitializerStartType.TYPE_PARALLEL }
        Log.d(TAG, "AppInitializersProvider 开始执行 并行")
        parallelList.parallelStream().forEach {
            MainScope().launch {
                Log.d(TAG, "AppInitializersProvider $it 初始化模块协程开始执行: ${this.coroutineContext}")
                it.init()
            }
        }
        Log.d(TAG, "AppInitializersProvider 结束执行 并行")
        seriesList.forEach {
            it.init()
        }
    }
}