package uts.sdk.modules.uniOauthGoogle

import io.dcloud.uts.UTSAndroid
import io.dcloud.uts.console

import android.content.Context
import android.os.SystemClock
import android.util.Base64
import android.util.Log
import androidx.credentials.ClearCredentialStateRequest
import androidx.credentials.Credential
import androidx.credentials.CredentialManager
import androidx.credentials.GetCredentialRequest
import androidx.credentials.GetCredentialResponse
import com.google.android.libraries.identity.googleid.GetGoogleIdOption
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONObject

object NativeCode {
	/**
	 * credentialManager 要求必须在协程环境进行调用
	 */
	private val coroutineScope = CoroutineScope(Dispatchers.IO)
	
	fun requestLogout(credentialManager:CredentialManager,options:CallKotlinLogOutOptions){
	
		val request = ClearCredentialStateRequest()
	
		coroutineScope.launch {
			try {
				credentialManager.clearCredentialState(request)
				options.complete(null)
			} catch (e: Exception) {
			   options.complete(e)
			}
		}
		
	}
	
    fun requestLogin(credentialManager:CredentialManager,request:GetCredentialRequest,options:CallKotlinLoginOptions){
        coroutineScope.launch {
			try {
				val result = credentialManager.getCredential(
					context = UTSAndroid.getUniActivity()!!,
					request = request
				)
				val userInfo = handleSignIn(result)
				if(userInfo == null){
					options.fail(null)
				}else{
					options.success(userInfo)
				}
			} catch (e : Exception) {
				options.fail(e)
			}
		}
    }
	
	fun handleFailure(e:Exception){
		console.log(e)
	}

	fun handleSignIn(result: GetCredentialResponse): GoogleLoginSuccess? {
		when (val credential = result.credential) {
			is GoogleIdTokenCredential -> {
				val idToken = credential.idToken
				// 验证 Token 并获取用户信息
				val user = getUserFromToken(idToken)
				// 更新 UI 或发送到服务器
				return user
			}
			else -> {
				// 处理其他类型的凭证（如密码）
				return null
			}
		}
	}

	fun getUserFromToken(idToken: String): GoogleLoginSuccess? {
		val parts = idToken.split(".")
		if (parts.size != 3) return null

		return try {
			val payload = String(Base64.decode(parts[1], Base64.URL_SAFE), Charsets.UTF_8)
			val json = JSONObject(payload)
			
			GoogleLoginSuccess(
				idToken = idToken,
				openId = json.optString("sub"),
				nickname = json.optString("name"),
				email = json.optString("email"),
				headimgurl = json.optString("picture")
			)
		} catch (e: Exception) {
			null
		}
	}
	
	
}




