package com.ejada.hmg.hmgwifi

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.wifi.*
import android.net.wifi.SupplicantState.ASSOCIATED
import android.net.wifi.SupplicantState.COMPLETED
import android.util.Log
import com.ejada.hmg.MainActivity
import com.ejada.hmg.utils.HMGUtils

class WPA(mainActivity: MainActivity, SSID:String) {
    private var TAG = "WPA"
    private var SSID = "GUEST-POC"
    private var wifiManager_: WifiManager? = null
    private var connectivityManager_: ConnectivityManager? = null

    init {
        wifiManager_ = mainActivity.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
        connectivityManager_ = mainActivity.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
    }

    fun connect(identity:String, password:String, completion: (status: Boolean, message: String) -> Unit) {
        if(wifiManager_ == null || connectivityManager_ == null){
            completion(false,"errorConnectingHmgNetwork")
            return
        }

        val wifiManager  = wifiManager_!!
        val connectivityManager = connectivityManager_!!

        // Initialize the WifiConfiguration object
        val enterpriseConfig = WifiEnterpriseConfig()
        val wifi = WifiConfiguration()
        wifi.SSID = """"$SSID""""
        wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP)
        wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X)
        enterpriseConfig.eapMethod = WifiEnterpriseConfig.Eap.PEAP
        enterpriseConfig.identity = identity
        enterpriseConfig.password = password
        wifi.enterpriseConfig = enterpriseConfig
        wifi.networkId = ssidToNetworkId(wifi.SSID)
        if (wifi.networkId == -1) {
            wifiManager.addNetwork(wifi)
        } else {
            Log.v(TAG, "WiFi found - updating it.\n")
            wifiManager.updateNetwork(wifi)
        }
        Log.v(TAG, "saving config.\n")
        wifiManager.saveConfiguration()
        wifi.networkId = ssidToNetworkId(wifi.SSID)

        Log.v(TAG, "wifi ID in device = " + wifi.networkId)

        var supState: SupplicantState
        val networkIdToConnect = wifi.networkId
        if (networkIdToConnect >= 0) {
            Log.v(TAG, "Start connecting...\n")

            // We disable the network before connecting, because if this was the last connection before
            // a disconnect(), this will not reconnect.
            wifiManager.disableNetwork(networkIdToConnect)
            wifiManager.enableNetwork(networkIdToConnect, true)

            val wifiInfo: WifiInfo = wifiManager.connectionInfo

            HMGUtils.timer(5000,false){
                supState = wifiInfo.supplicantState
                Log.i(TAG, "WifiWizard: Done connect to network : status =  $supState")
                val successStates = listOf(COMPLETED, ASSOCIATED)
                if (successStates.contains(COMPLETED /*supState*/))

                    completion(true,"Connected to internet Wifi")

                else
                    completion(false,"errorConnectingHmgNetwork")
            }

        } else {
            Log.v(TAG, "WifiWizard: cannot connect to network")
            completion(false,"errorConnectingHmgNetwork")
        }
    }

    /**
     * This method takes a given String, searches the current list of configured WiFi
     * networks, and returns the networkId for the network if the SSID matches. If not,
     * it returns -1.
     */
    @SuppressLint("MissingPermission")
    private fun ssidToNetworkId(ssid: String): Int {
        val currentNetworks = wifiManager_!!.configuredNetworks
        var networkId = -1

        // For each network in the list, compare the SSID with the given one
        for (test in currentNetworks) {
            if (test.SSID == ssid) {
                networkId = test.networkId
                break
            }
        }
        return networkId
    }
}