package com.ejada.hmg.hmgwifi

import android.annotation.SuppressLint
import com.ejada.hmg.utils.API
import com.ejada.hmg.MainActivity
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_Internet(flutterMainActivity: MainActivity) {
    private val TAG = "HMG_Wifi"
    private val TEST = true

    private var context = flutterMainActivity;

    private lateinit var completionListener: ((status: Boolean, message: String) -> Unit)

    private var SSID = "GUEST-POC"

    fun completionOnUiThread(status: Boolean, message: String){
        completionListener(status, message)
//        context.runOnUiThread {
//             .with(message){localized ->
//                completionListener(status, localized)
//            }
//        }
    }

    /*
	 * Helpful:
	 * http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically
	 */
    fun connectToHMGGuestNetwork(username: String, password: String, completion: (status: Boolean, message: String) -> Unit): HMG_Internet {
        completionListener = completion
        WpaEnterprise(context,SSID).connect(username,username) { status, message ->
            completionOnUiThread(status,message)
        }
        return this
    }

    private fun haveInternet(completion: ((status: Boolean) -> Unit)){
        if (TEST)
            completion(true)

        "https://captive.apple.com".httpGet().response { request, response, result ->
            result.fold(success = {
                val html = String(it).toLowerCase(Locale.ENGLISH)
                        .replace(" ", "", true)
                        .replace("\n","",true)
                val have = html.contains("<title>success</title>", true)
                completion(have)

            },failure = {
                completion(false)
            })
        }
    }

    private fun getWifiCredentials(patientId:String, success: ((String?,String?) -> Unit)){
        if (TEST){
            SSID = "GUEST-POC"
            success("2300", "0000")
            return
        }

        val jsonBody = """{
            "PatientID":$patientId
            "VersionID": 8.8,
            "Channel": 3,
            "LanguageID": 2,
            "IPAdress": "10.20.10.20",
            "generalid": "Cs2020@2016$2958",
            "PatientOutSA": 0,
            "SessionID": "@admin",
            "isDentalAllowedBackend": false,
            "DeviceTypeID": 2,
            "TokenID": "@admin",
            "PatientTypeID": 1,
            "PatientType": 1
            }""".trimMargin()
        API.WIFI_CREDENTIALS.
                httpPost()
                .jsonBody(jsonBody, Charsets.UTF_8)
                .response { request, response, result ->

                    result.fold(success = { data ->
                        val jsonString = String(data)
                        val jsonObject = JSONObject(jsonString)
                        if(!jsonObject.getString("ErrorMessage").equals("null")){
                            val errorMsg = jsonObject.getString("ErrorMessage")
                            completionOnUiThread(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")){
                                        try {
                                            val userName = object_.getString("UserName")
                                            val password = object_.getString("Password")
                                            success(userName, password)
                                        }catch (e:Exception){
                                            success(null, null)
                                        }
                                    }else{
                                        completionOnUiThread(false, "somethingWentWrong")
                                    }
                                }
                            }
                        }

                    },failure = { error ->
                        completionOnUiThread(false, "somethingWentWrong" )
                    })
                }
    }
}