package com.idvlibrary

import android.content.Context
import com.facebook.react.bridge.Arguments.createMap
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReadableMap
import com.idv.identity.platform.api.IDTFacade
import com.idv.identity.platform.api.IdentityPlatform


class IdvModuleImpl {

  fun getMetaInfo(context: Context, promise: Promise?) {
    println("getMetaInfo:${IdentityPlatform.getMetaInfo(context)}")
    promise?.resolve(IdentityPlatform.getMetaInfo(context))
  }

  fun install(context: Context, promise: Promise?) {
    IdentityPlatform.getInstance().install(context)
    promise?.resolve(null)
  }

  fun installWithOptions(context: Context, options: ReadableMap?, promise: Promise?) {
    val map = mutableMapOf<String, String>()
    // 安全调用，防止 options 为 null
    options?.let { readableMap ->
      val iterator = readableMap.keySetIterator()
      while (iterator.hasNextKey()) {
        val key = iterator.nextKey()
        readableMap.getString(key)?.let { value ->
          map[key] = value
        }
      }
    }
    println("installWithOptions $map")
    IdentityPlatform.getInstance().install(context, map)
    promise?.resolve(null)
  }

  fun verify(
    transactionId: String?,
    extParams: ReadableMap?,
    promise: Promise?
  ) {
    try {
      // 将 ReadableMap 转换为 Map
      val paramsMap: MutableMap<String?, String?> = HashMap<String?, String?>()
      if (extParams != null) {
        val iterator = extParams.keySetIterator()
        while (iterator.hasNextKey()) {
          val key = iterator.nextKey()
          paramsMap[key] = extParams.getString(key)
        }
      }

      // 调用你的原生验证方法
      IdentityPlatform.getInstance().verify(transactionId, paramsMap) {
        val map = createMap()
        map.putInt("code", it.code)
        map.putString("subCode", it.subCode)
        map.putString("message", it.message)
        promise?.resolve(map)
        true
      }

    } catch (e: Exception) {
      promise?.reject("VERIFY_ERROR", e.message)
    }
  }

  fun setCustomUIConfig(param: String?, promise: Promise?) {
    promise?.resolve(
      IdentityPlatform.getInstance().setCustomUIConfig(IDTFacade.EXT_PARAMS_CONFIG_JSON, param)
    )

  }

  companion object {
    const val NAME = "IdvLibrary"
  }
}
