package com.base.locationsharewhite.ui.main

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.locationsharewhite.R
import com.base.locationsharewhite.bean.ViewerBean
import com.base.locationsharewhite.databinding.ActivityLocationShareBinding
import com.base.locationsharewhite.helper.BaseActivity
import com.base.locationsharewhite.location.LocationShareListUtils
import com.base.locationsharewhite.location.LocationShareUtils
import com.base.locationsharewhite.location.LocationShareUtils.SHARE_STATE_FAILED
import com.base.locationsharewhite.location.LocationShareUtils.SHARE_STATE_MYSELF
import com.base.locationsharewhite.location.LocationShareUtils.SHARE_STATE_SHARED
import com.base.locationsharewhite.location.LocationShareUtils.SHARE_STATE_SUCCESS
import com.base.locationsharewhite.location.LocationStatusUtils
import com.base.locationsharewhite.ui.set.RenameActivity
import com.base.locationsharewhite.ui.views.DialogView.showViewerMoreDialog
import com.base.locationsharewhite.utils.BarUtils
import com.base.locationsharewhite.utils.LogEx
import com.base.locationsharewhite.utils.SpStringUtils
import com.base.locationsharewhite.utils.SpStringUtils.VIEWER_NICKNAME_KEY
import com.base.locationsharewhite.utils.SpStringUtils._DEVICE_NICKNAME_
import com.base.locationsharewhite.utils.ToastUtils.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 添加谁可以看我
 */
class LocationShareActivity : BaseActivity<ActivityLocationShareBinding>() {
    private val TAG = "LocationShareActivity"

    override val binding: ActivityLocationShareBinding by lazy {
        ActivityLocationShareBinding.inflate(layoutInflater)
    }
    private lateinit var adapter: ViewerAdapter


    @SuppressLint("NotifyDataSetChanged")
    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.WHITE)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        binding.editCode.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                binding.editCode.hint = ""
            } else {
                binding.editCode.hint = this.resources.getString(R.string.enter_others_location_code)
            }
        }

        binding.shimmerLayout.startShimmerAnimation()
        adapter = ViewerAdapter(switchAction = { item, isChecked ->
            val changeStatus = if (isChecked) 1 else 0
            LogEx.logDebug(TAG, "device=${item.device}")
            LocationStatusUtils.changeViewerStatus(item.device, changeStatus) { flag ->
                runOnUiThread {
                    if (flag) {
                        item.status = changeStatus
                    }
                    adapter.notifyDataSetChanged()
                }
            }
        })
        adapter.moreAction = { anchorView, viewerBean ->
            showViewerMoreDialog(anchorView, deleteAction = {
                LocationShareListUtils.deleteShare(viewerBean.device) {
                    runOnUiThread {
                        toast(it.toString())
                    }
                }
            }, renameAction = {
                startActivity(Intent(this, RenameActivity::class.java).apply {
                    putExtra("doWhat", RenameActivity.RENAME_VIEWER_NICK_NAME)
                    putExtra("device", viewerBean.device)
                    putExtra("nickName", viewerBean.localNickName ?: viewerBean.nickName)
                })
            })
        }
        binding.rv.adapter = adapter


        initShareData()
    }


    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            finish()
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.tvShare.setOnClickListener {
            val code = binding.editCode.text.toString()
            if (code.isEmpty()) {
                toast("code is empty")
                return@setOnClickListener
            }
            if (code.length >= 8) {
                LocationShareUtils.shareMyLocationByInvitationCode(code) { status ->
                    runOnUiThread {
                        when (status) {
                            SHARE_STATE_FAILED -> {
                                toast("Code verification failed")
                            }

                            SHARE_STATE_SUCCESS -> {
                                toast("Code verification success")
                                initShareData()
                            }

                            SHARE_STATE_SHARED -> {
                                toast("Sharing code has been added")
                            }

                            SHARE_STATE_MYSELF -> {
                                toast("Sharing code is yourself code")
                            }
                        }

                    }
                }
            } else {
                toast("code verification failed")
            }
        }
    }

    private fun initShareData() {
        LocationShareListUtils.getShareList(viewerListCallBack = {
            val nickList = SpStringUtils.getSpStringList(VIEWER_NICKNAME_KEY)
            it.forEach { viewer -> changeLocalNickName(viewer, nickList) }
            runOnUiThread {
                adapter.submitList(it)
            }
        })
    }

    override fun onResume() {
        super.onResume()
        refreshNickName()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun refreshNickName() = lifecycleScope.launch(Dispatchers.IO) {
        val nickList = SpStringUtils.getSpStringList(VIEWER_NICKNAME_KEY)

        adapter.items.map { viewer ->
            changeLocalNickName(viewer, nickList)
        }
        launch(Dispatchers.Main) {
            adapter.notifyDataSetChanged()
        }
    }

    private fun changeLocalNickName(viewer: ViewerBean, nickList: List<String>) {
        val deviceNicknameSp = nickList.find { it.contains(viewer.device) }
        deviceNicknameSp?.let { sp ->
            runCatching {
                val localNickName = sp.split(_DEVICE_NICKNAME_)[1]
                viewer.localNickName = localNickName
            }
        }
    }


}