package com.hmg.hmgDr

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.annotation.NonNull
import com.google.gson.GsonBuilder
import com.hmg.hmgDr.Model.GetSessionStatusModel
import com.hmg.hmgDr.Model.SessionStatusModel
import com.hmg.hmgDr.ui.VideoCallResponseListener
import com.hmg.hmgDr.ui.fragment.VideoCallFragment
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant


class MainActivity : FlutterFragmentActivity(), MethodChannel.MethodCallHandler, VideoCallResponseListener {

    private val CHANNEL = "Dr.cloudSolution/videoCall"
    private lateinit var methodChannel: MethodChannel
    private var result: MethodChannel.Result? = null
    private var call: MethodCall? = null
    private val LAUNCH_VIDEO: Int = 1

    private var dialogFragment: VideoCallFragment? = null

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine)

        methodChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
        methodChannel.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {

        this.result = result
        this.call = call

        when (call.method) {
            "openVideoCall" -> {
                val apiKey = call.argument<String>("kApiKey")
                val sessionId = call.argument<String>("kSessionId")
                val token = call.argument<String>("kToken")
                val appLang = call.argument<String>("appLang")
                val baseUrl = call.argument<String>("baseUrl")

                // Session Status model
                val VC_ID = call.argument<Int>("VC_ID")
                val tokenID = call.argument<String>("TokenID")
                val generalId = call.argument<String>("generalId")
                val doctorId = call.argument<Int>("DoctorId")
                val patientName = call.argument<String>("patientName")

                val sessionStatusModel = GetSessionStatusModel(VC_ID, tokenID, generalId, doctorId, patientName)


                openVideoCall(apiKey, sessionId, token, appLang, baseUrl, sessionStatusModel)

            }
            "closeVideoCall" -> {
                dialogFragment?.onCallClicked()
            }
            "onCallConnected" -> {

            }
            else -> {
                result.notImplemented()
            }
        }
    }

    private fun openVideoCall(apiKey: String?, sessionId: String?, token: String?, appLang: String?, baseUrl: String?, sessionStatusModel: GetSessionStatusModel) {
        if (dialogFragment == null) {
            val arguments = Bundle()
            arguments.putString("apiKey", apiKey)
            arguments.putString("sessionId", sessionId)
            arguments.putString("token", token)
            arguments.putString("appLang", appLang)
            arguments.putString("baseUrl", baseUrl)
            arguments.putParcelable("sessionStatusModel", sessionStatusModel)

            val transaction = supportFragmentManager.beginTransaction()
            dialogFragment = VideoCallFragment.newInstance(arguments)
            dialogFragment?.let {
                it.setCallListener(this)
                it.isCancelable = true
                if (it.isAdded){
                    it.dismiss()
                }else {
                    it.show(transaction, "dialog")
                }


            }
        } else if (!dialogFragment!!.isVisible) {
            val transaction = supportFragmentManager.beginTransaction()
            dialogFragment!!.show(transaction, "dialog")
        }
    }


    /* override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
         super.onActivityResult(requestCode, resultCode, data)
         var asd = "";
         if (requestCode == LAUNCH_VIDEO) {
             if (resultCode == Activity.RESULT_OK) {
                 val result  : SessionStatusModel? = data?.getParcelableExtra("sessionStatusNotRespond")
                 val callResponse : HashMap<String, String> = HashMap()

                 val sessionStatus : HashMap<String, String> = HashMap()
                 val gson = GsonBuilder().serializeNulls().create()

                 callResponse["callResponse"] = "CallNotRespond"
                 val jsonRes = gson.toJson(result)
                 callResponse["sessionStatus"] = jsonRes

                 this.result?.success(callResponse)
             }
             if (resultCode == Activity.RESULT_CANCELED) {
                 val callResponse : HashMap<String, String> = HashMap()
                 callResponse["callResponse"] = "CallEnd"

                 result?.success(callResponse)
             }
         }
     }*/

    override fun onCallFinished(resultCode: Int, intent: Intent?) {
        dialogFragment = null

        if (resultCode == Activity.RESULT_OK) {
            val result: SessionStatusModel? = intent?.getParcelableExtra("sessionStatusNotRespond")
            val callResponse: HashMap<String, String> = HashMap()

            val sessionStatus: HashMap<String, String> = HashMap()
            val gson = GsonBuilder().serializeNulls().create()

            callResponse["callResponse"] = "CallNotRespond"
            val jsonRes = gson.toJson(result)
            callResponse["sessionStatus"] = jsonRes

            try {
                this.result?.success(callResponse)
            } catch (e : Exception){
                Log.e("onVideoCallFinished", "${e.message}.")
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            val callResponse: HashMap<String, String> = HashMap()
            callResponse["callResponse"] = "CallEnd"
            try {
                result?.success(callResponse)
            } catch (e : Exception){
                Log.e("onVideoCallFinished", "${e.message}.")
            }
        }
    }

    override fun errorHandle(message: String) {
        dialogFragment = null
//        Toast.makeText(this, message, Toast.LENGTH_LONG).show()
    }

    override fun minimizeVideoEvent(isMinimize: Boolean) {
        if (isMinimize)
            methodChannel.invokeMethod("onCallConnected", null)
        else
            methodChannel.invokeMethod("onCallDisconnected", null)
    }

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

}
