package com.develop.setting.init.ui

import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.NetworkUtils
import com.develop.food.base.common.WIFI_FROM_MAIN_SETTING
import com.develop.food.base.event.FinishAtyEvent
import com.develop.food.base.event.RemoveWifiEvent
import com.develop.food.base.manager.wifi.WifiData
import com.develop.food.base.manager.wifi.WifiHelp
import com.develop.food.base.router.Screens
import com.develop.food.base.router.navigateTo
import com.develop.food.base.ui.BaseActivity
import com.develop.food.base.utils.GlobalToast
import com.develop.food.base.utils.ResDimension
import com.develop.setting.R
import com.develop.setting.databinding.ActivityWifiListBinding
import com.develop.setting.init.adapter.WifiListAdapter
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

@Route(path = Screens.Setting.WIFI)
class WifiListActivity : BaseActivity<ActivityWifiListBinding>() {
    private var wifiListAdapter = WifiListAdapter()
    private var isFromMainSetting = false
    private var wifiDataList = mutableListOf<WifiData>()
    private lateinit var wifiHelp: WifiHelp

    override fun createViewBinding(inflater: LayoutInflater): ActivityWifiListBinding {
        return ActivityWifiListBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isFromMainSetting = intent.extras?.getBoolean(WIFI_FROM_MAIN_SETTING) ?: false

        if (isFromMainSetting) {
            binding.tvSkin.visibility = View.GONE
        }

        binding.topBar.listenBackClick {
            finish()
        }
        binding.topBar.setTopBarTitle(getString(R.string.wifi))


        wifiListAdapter.apply {
            onOkClickListener = object : WifiListAdapter.OnOkClickListener {
                override fun onOkClick(accessPoint: WifiData) {
                    showDialog()
                    wifiHelp.connect(accessPoint, accessPoint.password)
                }
            }
            setOnItemClickListener { adapter, view, position ->
                val wifiData = wifiDataList[position]
                if (wifiData.isConnected) {
//                    GlobalToast.showToast("已连接")
                } else if (wifiData.password.isNotEmpty()) {
                    showDialog()
                    wifiHelp.connect(wifiData, wifiData.password)
                } else if (wifiData.isSavePwd) {
                    showDialog()
                    wifiHelp.connect(wifiData)
                } else {
                    updateSelectedPosition(position)
                }
            }
        }

        binding.wifiRecycler.apply {
            adapter = wifiListAdapter
            addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    super.getItemOffsets(outRect, view, parent, state)
                    val pos = parent.getChildAdapterPosition(view)
                    if (pos == 0) {
                        outRect.top = ResDimension(R.dimen.convert_30px).toInt()
                    }
                    outRect.left = ResDimension(R.dimen.convert_45px).toInt()
                    outRect.right = ResDimension(R.dimen.convert_45px).toInt()
                    outRect.bottom = ResDimension(R.dimen.convert_50px).toInt()
                }
            })
        }


        binding.tvSkin.setOnClickListener {
            if (NetworkUtils.isConnected()) {
                navigateTo(Screens.Auth.MEMBER)
            } else {
                navigateTo(Screens.Main.ENTRANCE_CHOSEN)
            }
            EventBus.getDefault().post(FinishAtyEvent())
            finish()
        }

        if (isFromMainSetting) {
            binding.tvNext.text = getText(R.string.confirm)
        }

        binding.tvNext.setOnClickListener {
            EventBus.getDefault().post(FinishAtyEvent())
            if (isFromMainSetting) {
                finish()
            } else {
                navigateTo(Screens.Auth.MEMBER)
            }

        }

        wifiHelp = WifiHelp.Build(this)
            .setErrorAuthenticating {
                dismissDialog()
                GlobalToast.showToast("连接失败")
            }
            .setScanCallback {
                it?.apply {
                    wifiDataList.clear()
                    wifiDataList.addAll(it)
                    wifiListAdapter.setList(wifiDataList)
                }
            }
            .setWifiStateChangedListener {

            }
            .setAlreadyConnectionCallback {
                dismissDialog()
            }
            .setNetworkStateChangedListener {

            }
            .build()
    }

    override fun onDestroy() {
        super.onDestroy()
        wifiHelp.destroy()
    }

    override fun onResume() {
        super.onResume()
        AndPermission.with(this).runtime().permission(
            Permission.ACCESS_FINE_LOCATION,
            Permission.ACCESS_BACKGROUND_LOCATION, Permission.ACCESS_COARSE_LOCATION
        )
            .onGranted {
                wifiHelp.scan()
            }.start()
    }


    @Subscribe
    fun onRemoveWifi(event:RemoveWifiEvent){
        wifiHelp.removeAllWifi()
    }


}