package com.ydl.ydlcommon.modular

import com.alibaba.android.arouter.exception.NoRouteFoundException
import com.alibaba.android.arouter.facade.template.IProvider
import com.alibaba.android.arouter.launcher.ARouter
import com.ydl.ydlcommon.utils.LogUtil



/**
 * Created by haorui on 2019-09-21 .
 * Des:查找 Arouter 服务封装类
 */
object ModularServiceManager {

    private val routerMap: HashMap<String, IProvider> = HashMap()

    fun getPlatformUserService(): IPlatformUserModuleService? {
        return provide(IPlatformUserModuleService::class.java)
    }

    fun <T : IProvider> provide(clz: Class<T>, path: String): T {

        var provider: IProvider? = null
        val simpleName = clz.simpleName;

        if (routerMap[simpleName]!=null){
            return routerMap[simpleName] as T
        }

        try {
            val navigation = ARouter.getInstance()
                .build(path)
                .navigation()
                ?: throw NoRouteFoundException("Please check if you are dependent on the module containing $simpleName , path is $path")

            provider = navigation as IProvider

            routerMap[simpleName] = provider

        } catch (e: Exception) {
            LogUtil.e(e.message)
        }

        return provider as T
    }

    fun <T : IProvider> provide(clz: Class<T>): T {

        var provider: IProvider? = null
        val simpleName = clz.simpleName;

        if (routerMap[simpleName]!=null){
            return routerMap[simpleName] as T
        }

        try {
            provider = ARouter.getInstance().navigation(clz)
            if (provider == null){
                throw NoRouteFoundException("Please check if you are dependent on the module containing $simpleName")
            }
            routerMap[simpleName] = provider
        } catch (e: Exception) {
            LogUtil.e(e.message)
        }

        return provider as T
    }
}