package com.develop.setting.ui

import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.NetworkUtils
import com.develop.base.ext.navigateTo
import com.develop.base.ext.resId2Dimension
import com.develop.base.ext.toJson
import com.develop.base.manager.WifiData
import com.develop.base.manager.WifiHelp
import com.develop.base.util.GlobalToast
import com.develop.common.event.FinishAtyEvent
import com.develop.common.router.Screens
import com.develop.common.tag.WIFI_FROM_MAIN_SETTING
import com.develop.common.ui.CommonBindingActivity
import com.develop.common.widget.WifiContentView
import com.develop.setting.R
import com.develop.setting.databinding.ActivityWifiListBinding
import com.drake.brv.utils.bindingAdapter
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import org.greenrobot.eventbus.EventBus

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

    private var selectedPosition = -1

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        initListener()
    }

    private fun initView() {
        isFromMainSetting = intent.extras?.getBoolean(WIFI_FROM_MAIN_SETTING) ?: false

        if (isFromMainSetting) {
            binding.tvSkin.visibility = View.GONE
            val params = binding.tvNext.layoutParams as RelativeLayout.LayoutParams
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
            params.bottomMargin = dp30
            binding.tvNext.text = getText(com.develop.common.R.string.confirm)
        }

        binding.wifiRecycler.apply {

            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 = dp30
                    }
                    outRect.left = dp45
                    outRect.right = dp45
                    outRect.bottom = dp50
                }
            })
            linear()
            setup {

                addType<WifiData>(R.layout.item_wifi_info)
                onClick{
                    Log.i("linzm","22wifi-debug,selectedPosition：${selectedPosition}，absoluteAdapterPosition：${absoluteAdapterPosition}")

                }
                onBind {
                    val model = getModel<WifiData>()
                    val wifiContent = findView<WifiContentView>(R.id.wifi_content)
                    wifiContent.setWifiModel(model)
                    wifiContent.onOkClickListener = object : WifiContentView.OnOkClickListener {
                        override fun onOkClick(wifiData: WifiData) {
                            wifiHelp.connect(wifiData, wifiData.password)
                        }

                        override fun onContentClick(wifiData: WifiData) {
                            val clickModel = wifiData
                            if (clickModel.isConnected) {
                                GlobalToast.showToast("connected successfully")
                            } else if (clickModel.password.isNotEmpty()) {
                                showPlainDialog()
                                wifiHelp.connect(clickModel, clickModel.password)
                            } else if (clickModel.isSavePwd) {
                                showPlainDialog()
                                wifiHelp.connect(clickModel)
                            } else {
                                updateSelectionPos(absoluteAdapterPosition)
                            }
                        }
                    }

                    Log.i("linzm","wifi-debug,selectedPosition：${selectedPosition}，absoluteAdapterPosition：${absoluteAdapterPosition},${model.toString()}")
                    wifiContent.showInputView(selectedPosition == absoluteAdapterPosition, model)

                    R.id.wifi_content.onLongClick {
                        wifiHelp.removeSaveWifi(wifiDataList[absoluteAdapterPosition])
                    }
                }
            }
        }.models = wifiDataList
    }

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

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

        wifiHelp = WifiHelp.Build(this).setErrorAuthenticating {
            dismissPlainDialog()
        }.setScanCallback {
            it?.apply {
                wifiDataList.clear()
                wifiDataList.addAll(it)
                binding.wifiRecycler.models = wifiDataList
                selectedPosition = -2
            }
        }.setWifiStateChangedListener {
            dismissPlainDialog()
        }.setAlreadyConnectionCallback {
            dismissPlainDialog()
        }.setNetworkStateChangedListener {
            dismissPlainDialog()
        }.build()
    }


    private fun updateSelectionPos(pos: Int) {
        binding.wifiRecycler.bindingAdapter.apply {
            val tempPosition = selectedPosition
            selectedPosition = pos
            notifyItemChanged(tempPosition)
            notifyItemChanged(selectedPosition)
        }
    }

    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()
    }

    companion object {
        var dp30 = (com.develop.base.R.dimen.convert_30px).resId2Dimension().toInt()
        var dp45 = (com.develop.base.R.dimen.convert_45px).resId2Dimension().toInt()
        var dp50 = (com.develop.base.R.dimen.convert_50px).resId2Dimension().toInt()
    }
}