package com.ydl.ydlcommon.modular

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()

            provider = navigation as IProvider

            routerMap[simpleName] = provider

        } catch (e: Exception) {
            LogUtil.e(e.message)
            return throw ServiceNotFoundException("请检查您是否依赖于包含以下内容的模块: $simpleName, path is $path")
        }

        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){
                LogUtil.e("provide : Service Not Found ")
            }
            routerMap[simpleName] = provider
        } catch (e: Exception) {
            LogUtil.e(e.toString())
            return throw ServiceNotFoundException("请检查您是否依赖于包含以下内容的模块: $simpleName")
        }

        return provider as T
    }

    /**
     * 用以判断是否接入依赖某业务模块
     */
    fun <T : IProvider> isDependByClz(clz: Class<T>): Boolean {
        var provider: IProvider? = null

        try {
            provider = ARouter.getInstance().navigation(clz)
            return provider != null
        } catch (e: Exception) {
            LogUtil.e(e.toString())
        }

        return provider != null
    }
}