package it.danieleverducci.openweddingapp.utils

import android.app.AlertDialog
import android.content.Context
import android.content.Context.WIFI_SERVICE
import android.content.DialogInterface
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.net.wifi.WifiNetworkSuggestion
import android.os.Build
import android.util.Log
import android.widget.Toast
import it.danieleverducci.openweddingapp.R
import it.danieleverducci.openweddingapp.entities.WifiNetwork


object WifiUtils {
    const val TAG = "WifiUtils"

    /**
     * Shows a dialog asking the user if he want to connect to the wedding's wifi network
     * If the user answers yes, adds the wedding wifi networks to system keychain
     */
    fun askToAddWeddingNetworks(context: Context, networks: List<WifiNetwork>) {
        if (networks.isEmpty()) {
            Log.e(TAG, "Network list is empty: ignoring connection to wifi dialog")
            return
        }

        val builder: AlertDialog.Builder = context.let {
            AlertDialog.Builder(it, R.style.AlertDialogCustom)
        }
        builder.apply {
            setMessage(R.string.dialog_wifinetwork_message)
            setTitle(R.string.dialog_wifinetwork_title)
            setPositiveButton(android.R.string.ok) { _, _ ->
                addWeddingNetworks(context, networks)
                Toast.makeText(context, R.string.dialog_wifinetwork_waitplease, Toast.LENGTH_LONG).show()
            }
            setNegativeButton(android.R.string.cancel) { dialog, _ ->
                dialog.dismiss()
            }
        }
        builder.create().show()
    }

    /**
     * Adds wedding wifi networks to system keychain
     */
    fun addWeddingNetworks(context: Context, networks: List<WifiNetwork>) {
        if (networks.isEmpty()) {
            Log.e(TAG, "Network list is empty: ignoring adding wifi connection")
            return
        }
        if (networks.isEmpty())
            return

        val wifiManager = context.getApplicationContext()
            .getSystemService(WIFI_SERVICE) as WifiManager
        val list: MutableList<WifiNetworkSuggestion> = ArrayList()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            for (network in networks) {
                val wifiNetworkSuggestionBuilder = WifiNetworkSuggestion.Builder()
                wifiNetworkSuggestionBuilder.setSsid(network.ssid)
                wifiNetworkSuggestionBuilder.setWpa2Passphrase(network.password)
                val wifiNetworkSuggestion = wifiNetworkSuggestionBuilder.build()
                list.add(wifiNetworkSuggestion)
            }

            wifiManager.removeNetworkSuggestions(ArrayList<WifiNetworkSuggestion>())
            wifiManager.addNetworkSuggestions(list)
        } else {
            var first = true
            for (network in networks) {
                val wifiConfig = WifiConfiguration()

                wifiConfig.SSID = String.format("\"%s\"", network.ssid)
                wifiConfig.preSharedKey = String.format("\"%s\"", network.password)

                val netId = wifiManager.addNetwork(wifiConfig)

                if (first) {
                    // First connection is the more important one. Try to connect.
                    wifiManager.disconnect()
                    wifiManager.enableNetwork(netId, true)
                    wifiManager.reconnect()
                    first = false
                }
            }
        }
    }
}