//package com.ejada.hmg.utils
//
//import android.annotation.SuppressLint
//import android.content.Context
//import android.net.ConnectivityManager
//import android.net.Network
//import android.net.NetworkCapabilities
//import android.net.NetworkRequest
//import android.net.wifi.ScanResult
//import android.net.wifi.WifiConfiguration
//import android.net.wifi.WifiManager
//import android.util.Log
//import com.ejada.hmg.utils.API
//import com.ejada.hmg.FlutterMainActivity
//import com.github.kittinunf.fuel.core.extensions.jsonBody
//import com.github.kittinunf.fuel.httpGet
//import com.github.kittinunf.fuel.httpPost
//import org.json.JSONObject
//import java.util.*
//
//
//@SuppressLint("MissingPermission")
//class HMG_Wifi_(flutterMainActivity: FlutterMainActivity) {
//    val TAG = "WIFI"
//    val TEST = true
//
//    var context = flutterMainActivity;
//    var completionListener: ((status: Boolean, message: String) -> Unit)? = null
//
//
//    private var SSID = "HMG-GUEST"
//    private var USER_NAME = ""
//    private var PASSWORD = ""
//    var NETWORK_ID = -1 // HMG-GUEST Assigned Network ID by Android
//    private lateinit var PATIENT_ID:String
//    /*
//	 * Helpful:
//	 * http://stackoverflow.com/questions/5452940/how-can-i-get-android-wifi-scan-results-into-a-list
//	 */
//    fun triggerWifiScan(context: Context) {
//        val wifi = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
//        wifi.startScan()
//    }
//
//    /*
//	 * Helpful:
//	 * http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically
//	 */
//    fun connectToWifiNetworkWith(patientId: String): HMG_Wifi_ {
//
//        val connectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
//
//        PATIENT_ID = patientId
//
//        val security = "OPEN"
//        val networkPass = ""
//        Log.d(TAG, "Connecting to SSID \"$SSID\" with password \"$networkPass\" and with security \"$security\" ...")
//
//        // You need to create WifiConfiguration instance like this:
//        val conf = WifiConfiguration()
//        conf.SSID = "\"" + SSID + "\""
//
//        if (security == "OPEN") {
//            conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
//        } else if (security == "WEP") {
//            conf.wepKeys[0] = "\"" + networkPass + "\""
//            conf.wepTxKeyIndex = 0
//            conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
//            conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40)
//        } else {
//            conf.preSharedKey = "\"" + networkPass + "\""
//        }
//
//        // Then, you need to add it to Android wifi manager settings:
//        val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
//
//        NETWORK_ID = wifiManager.addNetwork(conf)
//        Log.d(TAG, "Network ID: $NETWORK_ID")
//
//        //wifiManager.disconnect();
//        val result = wifiManager.enableNetwork(NETWORK_ID, true)
//        //wifiManager.reconnect();
//        wifiManager.saveConfiguration()
//
//        if(result == true){
//            authNetworkConnection(NETWORK_ID);
//        }else{
//            completionListener?.let { it(false, "Error connecting to HMG network") }
//        }
//        return this
//    }
//
//    private var authTimer:Timer? = null
//    fun authNetworkConnection(networkId: Int){
//        authTimer = Timer()
//        authTimer?.scheduleAtFixedRate(object : TimerTask() {
//            override fun run() {
//                if (connectedNetworkId() == networkId && connectedNetworkIPAddress() > 0) {
//                    authServerCall()
//                    authTimer?.cancel()
//                }
//            }
//
//        }, 2000, 1000)
//
//        // If wifi not connected in 5 sec terminate with fail status
//        Timer().schedule(object : TimerTask() {
//            override fun run() {
//                if (null != authTimer) {
//                    authTimer?.cancel()
//                    completionListener?.let { it(false, "Error connecting to HMG network") }
//                }
//            }
//        }, 5000)
//
//    }
//
//    fun authServerCall(){
//
//        fun call(){
//
//            forceNetworkCallOverWifi()
//
//            val params = listOf("cmd" to "authenticate", "password" to PASSWORD, "user" to USER_NAME)
//            val serverUrl = "https://captiveportal-login.hmg.com/cgi-bin/login"
////            val serverUrl = "http://192.168.102.223/cgi-bin/login"
//            serverUrl
//                    .httpPost(params)
//                    .timeout(10000)
//                    .response { request, response, result ->
//                        Log.v(TAG, response.statusCode.toString())
//
//                        haveInternet { have ->
//                            if(have){
//                                Log.v(TAG, "Connected to internet via $SSID network at HMG")
//                                completionListener?.let { it(true, "Successfully connected to the internet") }
//                            }else{
//                                Log.e(TAG, "failed to connect to internet via $SSID network at HMG")
//                                completionListener?.let { it(false, "Authentication failed or you are already using your credentials on another device") }
//                            }
//                        }
//                    }
//        }
//
//        haveInternet { has ->
//            if (has){
//                getAuthCredentials {
//                    call()
//                }
//            }else{
//                completionListener?.let { it(false, "You must have active internet connection to connect with HMG Network") }
//            }
//        }
//    }
//
//    fun haveInternet(completion: ((status: Boolean) -> Unit)){
//        if (TEST)
//            completion(true)
//
//        "https://captive.apple.com".httpGet().response { request, response, result ->
//            val have = response.statusCode == 200  && String(response.data).contains("<TITLE>Success</TITLE>", true)
//            completion(have)
//        }
//    }
//
//    fun getAuthCredentials(completion: (() -> Unit)){
//        if (TEST){
//            USER_NAME = "2300"
//            PASSWORD = "1820"
//            completion()
//            return
//        }
//
//        val jsonBody = """{"PatientID":$PATIENT_ID}"""
//        API.WIFI_CREDENTIALS
//                .httpPost()
//                .jsonBody(jsonBody, Charsets.UTF_8)
//                .response { request, response, result ->
//                    val jsonString = String(response.data)
//                    Log.d(TAG, "JSON $jsonString")
//
//                    if (response.statusCode == 200){
//
//                        val jsonObject = JSONObject(jsonString)
//                        if(!jsonObject.getString("ErrorMessage").equals("null")){
//                            val errorMsg = jsonObject.getString("ErrorMessage")
//                            completionListener?.let { it(false, errorMsg) }
//
//                        }else{
//                            jsonObject.getJSONArray("Hmg_SMS_Get_By_ProjectID_And_PatientIDList").let { array ->
//                                array.getJSONObject(0).let { object_ ->
//                                    if (object_.has("UserName") && object_.has("UserName")){
//                                        USER_NAME = object_.getString("UserName")
//                                        PASSWORD = object_.getString("Password")
//                                        completion()
//                                    }else{
//                                        completionListener?.let { it(false, "Failed to get your internet credentials") }
//                                    }
//                                }
//                            }
//                        }
//
//                    }else{
//                        completionListener?.let { it(false, "Failed to get your internet credentials") }
//                    }
//                }
//    }
//
//    fun forceNetworkCallOverWifi(){
//        val connectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
////        val network = Network
////        connectivityManager.activeNetwork
//        // Exit app if Network disappears.
//        // Exit app if Network disappears.
////        val networkCapabilities: NetworkCapabilities = ConnectivityManager.from(context).getNetworkCapabilities(network)
////        val networkCapabilities: NetworkCapabilities = connectivityManager.getNetworkCapabilities(network)
//
////        if (networkCapabilities == null) {
////            return
////        }
//
//        val mNetworkCallback = object : ConnectivityManager.NetworkCallback() {
//            override fun onLost(lostNetwork: Network?) {
////                if (network.equals(lostNetwork)){
////                    //GlyphLayout.done(false)
////                }
//            }
//        }
//        val builder: NetworkRequest.Builder = NetworkRequest.Builder()
////        for (transportType in networkCapabilities.getTransportTypes()) {
////            builder.addTransportType(transportType)
////        }
//        connectivityManager.registerNetworkCallback(builder.build(), mNetworkCallback)
//    }
//
//    /*
//	 * Helpful:
//	 * http://stackoverflow.com/questions/6517314/android-wifi-connection-programmatically
//	 */
//    fun getScanResultSecurity(result: ScanResult): String? {
//        val capabilities: String = result.capabilities
//        val securityModes = arrayOf("WEP", "PSK", "EAP")
//        for (securityMode in securityModes) {
//            if (capabilities.contains(securityMode)) {
//                return securityMode
//            }
//        }
//        return "OPEN"
//    }
//
//    //connects to the given ssid
//    fun connectToWPAWiFi(ssid: String, password: String){
//
//        WifiUtils.withContext(context)
//                .connectWith(ssid, "")
//                .setTimeout(40000)
//                .onConnectionResult(object : ConnectionSuccessListener {
//                    override fun success() {
//                        Log.v(TAG,"Success")
//                    }
//
//                    override fun failed(@NonNull errorCode: ConnectionErrorCode) {
//                        Log.v(TAG,"Failed")
//                    }
//                })
//                .start()
//        if(isConnectedTo(ssid)){ //see if we are already connected to the given ssid
//            return
//        }
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//            Log.e(TAG, "connection wifi  Q")
//
//            val wifiNetworkSpecifier: WifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
//                    .setSsid(ssid)
//                    .setWpa2Passphrase(password)
//                    .build()
//
//            val networkRequest: NetworkRequest = NetworkRequest.Builder()
//                    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
//                    .setNetworkSpecifier(wifiNetworkSpecifier)
//                    .build()
//
//            var connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
//            var networkCallback = object : ConnectivityManager.NetworkCallback() {
//                override fun onAvailable(network: Network) {
//                    super.onAvailable(network)
//                    connectivityManager.bindProcessToNetwork(network)
//                    Log.e(TAG, "onAvailable")
//                }
//
//                override fun onLosing(network: Network, maxMsToLive: Int) {
//                    super.onLosing(network, maxMsToLive)
//                    Log.e(TAG, "onLosing")
//                }
//
//                override fun onLost(network: Network) {
//                    super.onLost(network)
//                    Log.e(TAG, "onLosing")
//                    Log.e(TAG, "losing active connection")
//                }
//
//                override fun onUnavailable() {
//                    super.onUnavailable()
//                    Log.e(TAG, "onUnavailable")
//                }
//            }
//            connectivityManager.requestNetwork(networkRequest, networkCallback)
//
//        }else{
//
//            try {
//                val wm:WifiManager= context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
//
//                Log.e(TAG, "connection wifi pre Q")
//
//                var netId: Int = wm.addNetwork(getWifiConfig(ssid))
//                if (netId == -1) netId = getExistingNetworkId(ssid);
//                wm.saveConfiguration()
//                if(wm.enableNetwork(netId, true)){
//                    Log.v(TAG,"HMG-GUEST Connected")
//                }else{
//                    Log.v(TAG,"HMG-GUEST failed to connect")
//                }
//            } catch (e: Exception) {
//                e.printStackTrace()
//                Log.v(TAG,"HMG-GUEST failed to connect")
//            }
//        }
//
//    }
//
//    fun connectedNetworkId():Int{
//        val wm:WifiManager= context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
//        return wm.connectionInfo.networkId
//    }
//
//    fun connectedNetworkIPAddress():Int{
//        val wm:WifiManager= context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
//        return wm.connectionInfo.ipAddress
//    }
//
//    fun isConnectedTo(bssid: String):Boolean{
//        val wm:WifiManager= context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
//        if(wm.connectionInfo.bssid == bssid){
//            return true
//        }
//        return false
//    }
//
//}