package com.ejada.hmg.utils

import android.content.Context
import android.net.wifi.WifiManager
import android.util.Log
import com.ejada.hmg.MainActivity
import com.ejada.hmg.hmgwifi.HMG_Guest
import com.ejada.hmg.hmgwifi.HMG_Internet
import com.ejada.hmg.geofence.GeoZoneModel
import com.ejada.hmg.geofence.HMG_Geofence
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

class PlatformBridge(binaryMessenger: BinaryMessenger, flutterMainActivity: MainActivity) {
    private var binaryMessenger = binaryMessenger
    private var mainActivity = flutterMainActivity

    private lateinit var channel: MethodChannel

    companion object {
        private const val CHANNEL = "HMG-Platform-Bridge"
        private const val HMG_INTERNET_WIFI_CONNECT_METHOD = "connectHMGInternetWifi"
        private const val HMG_GUEST_WIFI_CONNECT_METHOD = "connectHMGGuestWifi"
        private const val ENABLE_WIFI_IF_NOT = "enableWifiIfNot"
        private const val REGISTER_HMG_GEOFENCES = "registerHmgGeofences"
        private const val UN_REGISTER_HMG_GEOFENCES = "unRegisterHmgGeofences"
    }

    fun create(){
        channel = MethodChannel(binaryMessenger, CHANNEL)
        HMGUtils.setPlatformChannel(channel)
        channel.setMethodCallHandler { methodCall: MethodCall, result: MethodChannel.Result ->

            if (methodCall.method == HMG_INTERNET_WIFI_CONNECT_METHOD) {
                connectHMGInternetWifi(methodCall,result)

            }else if (methodCall.method == HMG_GUEST_WIFI_CONNECT_METHOD) {
                connectHMGGuestWifi(methodCall,result)

            }else if (methodCall.method == ENABLE_WIFI_IF_NOT) {
                enableWifiIfNot(methodCall,result)
            }else if (methodCall.method == REGISTER_HMG_GEOFENCES) {
                registerHmgGeofences(methodCall,result)
            }else if (methodCall.method == UN_REGISTER_HMG_GEOFENCES) {
                unRegisterHmgGeofences(methodCall,result)
            }else{

                result.notImplemented()
            }

        }

        val res = channel.invokeMethod("localizedValue","errorConnectingHmgNetwork")
        print(res)
    }

    private fun connectHMGInternetWifi(methodCall: MethodCall, result: MethodChannel.Result){
        (methodCall.arguments as ArrayList<*>).let {
            require(it.size > 0 && (it[0] is String),lazyMessage = {
                "Missing or invalid arguments (Must have one argument 'String at 0'"
            })

            val patientId = it[0].toString()
            HMG_Internet(mainActivity)
                    .connectToHMGGuestNetwork(patientId){ status, message ->

                        mainActivity.runOnUiThread {
                            result.success(if(status) 1 else 0)

                            HMGUtils.popFlutterText(mainActivity, message)
                            Log.v(this.javaClass.simpleName, "$status | $message")
                        }

                    }
        }
    }


    private fun connectHMGGuestWifi(methodCall: MethodCall, result:  MethodChannel.Result){
        HMG_Guest(mainActivity).connectToHMGGuestNetwork { status, message ->
            mainActivity.runOnUiThread {
                result.success(if(status) 1 else 0)

                HMGUtils.popFlutterText(mainActivity, message)
                Log.v(this.javaClass.simpleName, "$status | $message")
            }
        }
    }

    private fun enableWifiIfNot(methodCall: MethodCall, result: MethodChannel.Result) {
        val wm = mainActivity.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
        if (wm != null){
            if (!wm.isWifiEnabled)
                wm.isWifiEnabled = true
            result.success(true)
        }else
            result.error("101","Error while opening wifi, Please try to open wifi yourself and try again","'WifiManager' service failed");
    }


    private fun registerHmgGeofences(methodCall: MethodCall, result: MethodChannel.Result) {

        channel.invokeMethod("getGeoZones",null, object : MethodChannel.Result{
            override fun success(result: Any?) {
                if(result is String) {
                    val geoZones = GeoZoneModel().listFrom(result)
                    HMG_Geofence.shared(mainActivity).register(){ s, e -> }
                }
            }

            override fun error(errorCode: String?, errorMessage: String?, errorDetails: Any?) { print(result) }
            override fun notImplemented() { print(result) }
        })

    }
    
    private fun unRegisterHmgGeofences(methodCall: MethodCall, result: MethodChannel.Result) {
        HMG_Geofence.shared(mainActivity).unRegisterAll { status, exception ->
            if(status)
                result.success(true)
            else
                result.error("101", exception?.localizedMessage, exception);
        }
    }
    
}
