package com.gh.gamecenter.ksp.compiler.utils

import com.gh.gamecenter.ksp.compiler.entity.TypeKind
import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.symbol.KSPropertyDeclaration

/**
 * AutoWire Inject Field Type check and convert
 * */
internal fun KSPropertyDeclaration.typeExchange(): Int {
    val type = this.type.resolve()
    @Suppress("KotlinConstantConditions")
    return when (type.declaration.qualifiedName?.asString()) {
        Consts.KBYTE -> TypeKind.BYTE.ordinal
        Consts.KSHORT -> TypeKind.SHORT.ordinal
        Consts.KINTEGER -> TypeKind.INT.ordinal
        Consts.KLONG -> TypeKind.LONG.ordinal
        Consts.KFLOAT -> TypeKind.FLOAT.ordinal
        Consts.KDOUBEL -> TypeKind.DOUBLE.ordinal
        Consts.KBOOLEAN -> TypeKind.BOOLEAN.ordinal
        Consts.KCHAR -> TypeKind.CHAR.ordinal
        Consts.KSTRING -> TypeKind.STRING.ordinal
        else -> {
            when (this.isSubclassOf(listOf(Consts.PARCELABLE, Consts.SERIALIZABLE))) {
                0 -> TypeKind.PARCELABLE.ordinal
                1 -> TypeKind.SERIALIZABLE.ordinal
                else -> TypeKind.OBJECT.ordinal
            }
        }
    }
}

/**
 *  Find module name from ksp arguments, please add this config
 *  " ksp { arg("AROUTER_MODULE_NAME", project.getName()) } "
 *  in your module's build.gradle
 * */
@Suppress("SpellCheckingInspection")
internal fun Map<String, String>.findModuleName(logger: KSPLogger): String {
    val name = this[Consts.KEY_MODULE_NAME]
    return if (!name.isNullOrEmpty()) {
        @Suppress("RegExpSimplifiable", "KotlinConstantConditions")
        name.replace("[^0-9a-zA-Z_]+".toRegex(), "")
    } else {
        logger.error(Consts.NO_MODULE_NAME_TIPS_KSP)
        throw RuntimeException("ARouter::Compiler >>> No module name, for more information, look at gradle log.")
    }
}
