package com.stove.unity

import androidx.annotation.Keep
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context.CLIPBOARD_SERVICE
import android.os.Build
import android.webkit.WebView
import android.widget.Toast
import com.unity3d.player.UnityPlayer
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.games.AuthenticationResult
import com.google.android.gms.games.PlayGames
import com.google.android.gms.games.PlayGamesSdk
import com.google.android.gms.tasks.Task
import com.stove.base.result.Result.Companion.SuccessResult
import com.stove.base.result.Result.Companion.CanceledResult
import com.stove.base.result.Result.Companion.makeServerErrorResult
import com.stove.base.result.Result.Companion.ServerResponseCodeJSONExceptionKey
import com.stove.base.util.Utils

@Keep
object UnitySampleWrapper {

    private var sessionId: String = ""

    @JvmStatic
    fun setWebContentsDebuggingEnabled() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            UnityPlayer.currentActivity.runOnUiThread {
                WebView.setWebContentsDebuggingEnabled(true)
            }
        }
    }

    @JvmStatic
    fun initializeGPG() {
        /** GPG PC **/
        val runningPlatformType = Utils.getRunningPlatformType(UnityPlayer.currentActivity)
        println("## runningPlatformType($runningPlatformType)")
        Toast.makeText(UnityPlayer.currentActivity, "runningPlatformType : $runningPlatformType", Toast.LENGTH_LONG).show()
        
        PlayGamesSdk.initialize(UnityPlayer.currentActivity)
    }

    @JvmStatic
    fun getSessionId(): String {
        return sessionId
    }

    @JvmStatic
    fun signInGPG() {
        println("## signInGPG()")
        val gamesSignInClient = PlayGames.getGamesSignInClient(UnityPlayer.currentActivity)
        gamesSignInClient.isAuthenticated.addOnCompleteListener { isAuthenticatedTask: Task<AuthenticationResult> ->
            val isAuthenticated = isAuthenticatedTask.isSuccessful && isAuthenticatedTask.result.isAuthenticated
            println("## isAuthenticated($isAuthenticated)")
            if (isAuthenticated) {
                PlayGames.getRecallClient(UnityPlayer.currentActivity).requestRecallAccess().addOnSuccessListener { recallAccess ->
                    sessionId = recallAccess.sessionId
                    println("## sessionId($sessionId)")
		    Toast.makeText(UnityPlayer.currentActivity, "sessionId($sessionId)", Toast.LENGTH_SHORT).show()
                    
                    PlayGames.getPlayersClient(UnityPlayer.currentActivity).currentPlayer.addOnCompleteListener { players ->
                        println("## currentPlayer(${players.result})")
                        val clipboard = UnityPlayer.currentActivity.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                        clipboard.setPrimaryClip(ClipData.newPlainText("sessionId", sessionId))
                        clipboard.setPrimaryClip(ClipData.newPlainText("playerId", players.result.playerId))
                    }
                    //listener(SuccessResult, recallSessionId)
                }.addOnFailureListener { e ->
                    e.printStackTrace()
                    //listener(makeServerErrorResult(ServerResponseCodeJSONExceptionKey, e.toString()), "")
                }.addOnCanceledListener {
                    println("## cancled!")
                    //listener(CanceledResult, "")
                }

                PlayGames.getPlayersClient(UnityPlayer.currentActivity).currentPlayer.addOnCompleteListener {

                }
            } else {
                println("## start -> googleSignInClient.signInIntent!")
                val googleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN).requestEmail().requestId().build()
                val googleSignInClient = GoogleSignIn.getClient(UnityPlayer.currentActivity, googleSignInOptions)
                UnityPlayer.currentActivity.startActivityForResult(googleSignInClient.signInIntent, 9001)
            }
        }
    }
}