
package com.ydl.ydlcommon.utils

import android.content.Context
import android.content.pm.PackageManager
import com.ydl.ydlcommon.base.config.IConfigModule
import java.util.*

/**
 * Created by haorui on 2019-08-22 .
 * Des: 用于解析 AndroidManifest 中的 Meta 属性
 */
class ManifestParser(private val context: Context) {

    fun parse(): List<IConfigModule> {
        val modules = ArrayList<IConfigModule>()
        try {
            val appInfo = context.packageManager.getApplicationInfo(
                context.packageName, PackageManager.GET_META_DATA
            )
            if (appInfo.metaData != null) {
                for (key in appInfo.metaData.keySet()) {
                    if (MODULE_VALUE == appInfo.metaData.get(key)) {
                        modules.add(parseModule(key))
                    }
                }
            }
        } catch (e: PackageManager.NameNotFoundException) {
            throw RuntimeException("Unable to find metadata to parse IConfigModule", e)
        }

        return modules
    }

    companion object {
        private val MODULE_VALUE = "ModuleConfig"

        private fun parseModule(className: String): IConfigModule {
            val clazz: Class<*>
            try {
                clazz = Class.forName(className)
            } catch (e: ClassNotFoundException) {
                throw IllegalArgumentException("Unable to find IConfigModule implementation", e)
            }

            val module: Any
            try {
                module = clazz.newInstance()
            } catch (e: InstantiationException) {
                throw RuntimeException("Unable to instantiate IConfigModule implementation for $clazz", e)
            } catch (e: IllegalAccessException) {
                throw RuntimeException("Unable to instantiate IConfigModule implementation for $clazz", e)
            }

            if (module !is IConfigModule) {
                throw RuntimeException("Expected instanceof IConfigModule, but found: $module")
            }
            return module
        }
    }
}