package com.nxp.vizncompanionapp.utility

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.wifi.WifiManager
import com.nxp.vizncompanionapp.interfaces.SearchCallBack

class WifiHelper(context: Context, b: Boolean) {
    private var mContext: Context? = null
    private var mWifiManager: WifiManager? = null
    private var searching = false
    private var mSearchCallBack: SearchCallBack? = null

    init {
        this.mContext = context
        mWifiManager = mContext?.getSystemService(Context.WIFI_SERVICE) as WifiManager
        mWifiManager!!.isWifiEnabled = b
    }


    fun setSearchCallBack(mSearchCallBack: SearchCallBack) {
        this.mSearchCallBack = mSearchCallBack
    }

    fun startSearching() {

        if (mSearchCallBack == null) {
            return
        }
        mContext?.registerReceiver(mBroadcastReceiver, IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))

        mWifiManager?.startScan()
        searching = true
    }

    fun stopSearching() {
        try {
            mContext?.unregisterReceiver(mBroadcastReceiver)
            searching = false
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    fun isSearching(): Boolean {
        return searching
    }

    private val mBroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if(mSearchCallBack!=null)
            mSearchCallBack?.onNetworkDiscovered(mWifiManager?.scanResults!!)
        }
    }
}