package com.example.defenseapplication.liveVideo

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.defenseapplication.R
import com.example.defenseapplication.adapter.WifiListAdapter
import com.example.defenseapplication.databinding.DialogWifiListBinding
import com.example.defenseapplication.databinding.WifiManagementActivityBinding
import com.gyf.immersionbar.ImmersionBar
//WiFi管理
class WiFiManagementActivity : AppCompatActivity() {

    private lateinit var binding: WifiManagementActivityBinding
    private lateinit var wifiManager: WifiManager
    private lateinit var wifiScanReceiver: BroadcastReceiver
    private var popupWindow: PopupWindow? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = WifiManagementActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topBar)
            .init()
        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.btnSelectWifi.setOnClickListener {
            showWifiListDialog()
        }

        binding.etWifiName.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

            override fun afterTextChanged(s: Editable?) {
                updateBottomButtonVisibility()
            }
        })
        wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

        wifiScanReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                val success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)
                if (success) {
                    updateWifiList()
                }
            }
        }
        //点击确定成功失败吐司
        binding.btnConfirm.setOnClickListener {
//            if(){
//                ToastUtils.showSuccess(this, getString(R.string.wifi_connection_success))
//            }else{
//                ToastUtils.showError(this, getString(R.string.wifi_connection_failed))
//            }

        }
    }

    private fun showWifiListDialog() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED ||
            ActivityCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE)
            != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CHANGE_WIFI_STATE),
                1001)
            return
        }

        if (!wifiManager.isWifiEnabled) {
            wifiManager.isWifiEnabled = true
        }

        wifiManager.startScan()

        val dialogBinding = DialogWifiListBinding.inflate(LayoutInflater.from(this))
        popupWindow = PopupWindow(
            dialogBinding.root,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        ).apply {
            isFocusable = true
            setBackgroundDrawable(null)
            setOnDismissListener {
                binding.maskView.visibility = android.view.View.GONE
            }
            showAtLocation(window.decorView, Gravity.BOTTOM, 0, 0)
        }

        binding.maskView.visibility = android.view.View.VISIBLE

        dialogBinding.rvWifiList.layoutManager = LinearLayoutManager(this@WiFiManagementActivity)

        val wifiList = getWifiList()
        dialogBinding.rvWifiList.adapter = WifiListAdapter(wifiList) { wifiName ->
            binding.etWifiName.setText(wifiName)
            popupWindow?.dismiss()
        }
    }

    private fun updateBottomButtonVisibility() {
        val wifiName = binding.etWifiName.text.toString().trim()
        binding.bottomButtonLayout.visibility =
            if (wifiName.isNotEmpty()) android.view.View.VISIBLE else android.view.View.GONE
    }

    private fun getWifiList(): List<String> {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
            return emptyList()
        }
        val results: List<ScanResult> = wifiManager.scanResults
        return results.map { it.SSID }.distinct()
    }

    private fun updateWifiList() {
        popupWindow?.contentView?.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.rvWifiList)?.let { recyclerView ->
            val wifiList = getWifiList()
            recyclerView.adapter = WifiListAdapter(wifiList) { wifiName ->
                binding.etWifiName.setText(wifiName)
                popupWindow?.dismiss()
            }
        }
    }

    override fun onStart() {
        super.onStart()
        val intentFilter = IntentFilter()
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
        registerReceiver(wifiScanReceiver, intentFilter)
    }

    override fun onStop() {
        super.onStop()
        unregisterReceiver(wifiScanReceiver)
        popupWindow?.dismiss()
    }
}