package com.ejada.hmg.hmgwifi

import android.annotation.SuppressLint
import com.ejada.hmg.utils.API
import com.ejada.hmg.MainActivity
import com.ejada.hmg.utils.FlutterText
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 = false

    private var context = flutterMainActivity;

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

    private var SSID = "GUEST-POC"
    private var USER_NAME = ""
    private var PASSWORD = ""

    fun completionOnUiThread(status: Boolean, message: String){
        completionListener(status, message)
//        context.runOnUiThread {
//
//            FlutterText.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(patientId: String, completion: (status: Boolean, message: String) -> Unit): HMG_Internet {
        completionListener = completion
        getWifiCredentials(patientId) {
            WPA(context,SSID).connect(USER_NAME,PASSWORD) { 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: (() -> Unit)){
        if (TEST){
            SSID = "GUEST-POC"
            USER_NAME = "0696"
            PASSWORD = "0000"
            success()
            return
        }

        val jsonBody = """{"PatientID":$patientId}"""
        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")){
                                        USER_NAME = object_.getString("UserName")
                                        PASSWORD = object_.getString("Password")
                                        success()
                                    }else{
                                        completionOnUiThread(false, "somethingWentWrong")
                                    }
                                }
                            }
                        }

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