@file:JvmName("AppActivity")
/****************************************************************************
 * Copyright (c) 2015-2016 Chukong Technologies Inc.
 * Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
 *
 * http://www.cocos2d-x.org
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.(
 */
package com.cocos.game

import android.content.Intent
import android.content.res.Configuration
import android.net.Uri
import android.os.Bundle
import com.cocos.lib.CocosActivity
import com.cocos.lib.CocosHelper
import com.cocos.lib.CocosJavascriptJavaBridge
import com.cocos.service.SDKWrapper
import com.example.walletconnect_demo.server.BridgeServer
import com.google.gson.Gson
import com.squareup.moshi.Moshi
import okhttp3.OkHttpClient
import org.komputing.khex.extensions.toNoPrefixHexString
import org.walletconnect.Session
import org.walletconnect.impls.*
import org.walletconnect.nullOnThrow
import java.io.File
import java.util.*


public class AppActivity : CocosActivity(), Session.Callback {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508
        if (!isTaskRoot()) {
            // Android launched another instance of the root activity into an existing task
            //  so just quietly finish and go away, dropping the user back into the activity
            //  at the top of the stack (ie: the last state of this task)
            // Don't need to finish it again since it's finished in super.onCreate .
            return
        }
        // DO OTHER INITIALIZATION BELOW
        SDKWrapper.shared().init(this)
//        initBridge()
        initMoshi()
        initClient()
        initSessionStorage()

        instance = this;
    }

    override fun onStatus(status: Session.Status) {
        when(status) {
            Session.Status.Approved -> sessionApproved()
            Session.Status.Closed -> sessionClosed()
            Session.Status.Connected,
            Session.Status.Disconnected,
            is Session.Status.Error -> {
                // Do Stuff
            }
        }
    }

    override fun onMethodCall(call: Session.MethodCall) {
    }

    private fun sessionApproved() {
        println("--------sessionApproved--------------")
        var t = session.approvedAccounts()!![0];
        println(t);
//        CocosJavascriptJavaBridge.evalString("window.setAddress(${t})")
        CocosHelper.runOnGameThread { CocosJavascriptJavaBridge.evalString("window.setAddress('${t.toString()}')") }
//        CocosJavascriptJavaBridge.evalString("console.log(\"Javascript Java bridge!\")");
        println(session.approvedAccounts())
    }

    private fun sessionClosed() {
        println("--------sessionClosed--------------")
        println(session.approvedAccounts())
    }

    private fun initClient() {
        client = OkHttpClient.Builder().build()
    }

    private fun initMoshi() {
        moshi = Moshi.Builder().build()
    }

    private fun initBridge() {
        bridge = BridgeServer(moshi)
        bridge.start()
    }

    private fun initSessionStorage() {
        storage = FileWCSessionStore(File(cacheDir, "session_store.json").apply { createNewFile() }, moshi)
    }

    override fun onResume() {
        super.onResume()
        SDKWrapper.shared().onResume()
    }

    override fun onPause() {
        super.onPause()
        SDKWrapper.shared().onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508
        if (!isTaskRoot()) {
            return
        }
        SDKWrapper.shared().onDestroy()
    }

//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
//        super.onActivityResult(requestCode, resultCode, data)
//        SDKWrapper.shared().onActivityResult(requestCode, resultCode, data)
//    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        SDKWrapper.shared().onNewIntent(intent)
    }

    override fun onRestart() {
        super.onRestart()
        SDKWrapper.shared().onRestart()
    }

    override fun onStop() {
        super.onStop()
        SDKWrapper.shared().onStop()
    }

    override fun onBackPressed() {
        SDKWrapper.shared().onBackPressed()
        super.onBackPressed()
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        SDKWrapper.shared().onConfigurationChanged(newConfig)
        super.onConfigurationChanged(newConfig)
    }

    override protected fun onRestoreInstanceState(savedInstanceState: Bundle) {
        SDKWrapper.shared().onRestoreInstanceState(savedInstanceState)
        super.onRestoreInstanceState(savedInstanceState)
    }

    override protected fun onSaveInstanceState(outState: Bundle) {
        SDKWrapper.shared().onSaveInstanceState(outState)
        super.onSaveInstanceState(outState)
    }

    override protected fun onStart() {
        SDKWrapper.shared().onStart()
        super.onStart()
    }


    override fun onLowMemory() {
        SDKWrapper.shared().onLowMemory()
        super.onLowMemory()
    }

    fun test(){
    }

    companion object {
        lateinit var instance: AppActivity ;
        private lateinit var client: OkHttpClient
        private lateinit var moshi: Moshi
        private lateinit var bridge: BridgeServer
        private lateinit var storage: WCSessionStore
        lateinit var config: Session.Config
        lateinit var session: Session

        fun resetSession() {
            nullOnThrow { session }?.clearCallbacks()
            val key = ByteArray(32).also { Random().nextBytes(it) }.toNoPrefixHexString()
            config = Session.Config(UUID.randomUUID().toString(), "https://bridge.walletconnect.org/", key)
            session = WCSession(config,
                MoshiPayloadAdapter(moshi),
                storage,
                OkHttpTransport.Builder(client, moshi),
                Session.PeerMeta(name = "Example App")
            )
            session.offer()
        }
        @JvmStatic public fun initWallet() {
            println("--------initWallet--------------")
            resetSession()
            session.addCallback(instance)
            val i = Intent(Intent.ACTION_VIEW)
            i.data = Uri.parse(config.toWCUri())
            instance.startActivity(i)
            // instance.test()
        }
        ///解析庄给的json字符串  并且使用custom方法发送给钱包
        @JvmStatic public fun sendCustomMessage(jsonStr:String):String{
            ///解析成实体类
            var str = Gson().fromJson(jsonStr,argsModel::class.java);
            session.performMethodCall(
                Session.MethodCall.Custom(
                    System.currentTimeMillis(),
                    str.method!!,
                    str.params!!,
                ),
                ::handleResponse
            )
            val intent = Intent(Intent.ACTION_VIEW)
            intent.data = Uri.parse("wc:")
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            instance.startActivity(intent)
            return "ok"
        }
        private fun handleResponse(resp: Session.MethodCall.Response) {
            println(resp.result as? String)
        }
    }
}
class argsModel {
    var method: String? = null
    var params: List<Any>? = null

    override fun toString(): String {
        return "argsModel(method=$method, params=$params)"
    }
}

