package com.lovense.sdkdemo

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.lovense.sdkdemo.databinding.ActivityMainBinding
import com.lovense.sdklibrary.Lovense
import com.lovense.sdklibrary.LovenseToy
import com.lovense.sdklibrary.callBack.LovenseError
import com.lovense.sdklibrary.callBack.OnSearchToyListener
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

open class MainActivity : AppCompatActivity() {
    private var toyList: MutableList<LovenseToy> = ArrayList()
    private var toyAdapter: ToyAdapter? = null

    private val TAG = MainActivity::class.java.simpleName
    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        EventBus.getDefault().register(this)
        Lovense.getInstance(application).setLogEnable(true)
        Lovense.getInstance(application).setDeveloperToken("Your Token")
        binding.btnToken.setOnClickListener {
            Lovense.getInstance(application).setDeveloperToken(binding.etToken.text.toString())
        }

        binding.startScan.setOnClickListener { requestPermissions() }
        binding.stopScan.setOnClickListener {
            Lovense.getInstance(application).stopSearching()
            binding.title.text = "search toy(stop scan)"
        }
        binding.title.setOnClickListener {
            Lovense.getInstance(application).listToys { lovenseError ->

            }
        }

        val manager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        toyAdapter = ToyAdapter(this, toyList)
        binding.recylerView.layoutManager = manager
        binding.recylerView.adapter = toyAdapter
    }

    private fun scanDev() {
        toyList.clear()
        toyAdapter?.notifyDataSetChanged()
        Toast.makeText(this@MainActivity, "start scan！", Toast.LENGTH_SHORT).show()
        binding.title.text = "search toy(scaning)"

        Lovense.getInstance(application).searchToys(object : OnSearchToyListener {
            override fun onSearchToy(toy: LovenseToy) {
                runOnUiThread { addDevice(toy) }
            }

            override fun finishSearch() {
                Lovense.getInstance(application).saveToys(toyList) { }
                binding.title.text = "search toy(stop scan)"
            }

            override fun onError(msg: LovenseError) {
                Toast.makeText(this@MainActivity, msg.message, Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun addDevice(toy: LovenseToy?) {
        if (toy != null && !isAdded(toy.toyId)) {
            toyList.add(toy)
            toyAdapter?.notifyDataSetChanged()
        }
    }

    private fun isAdded(toyId: String?): Boolean {
        return toyList.any { !it.toyId.isNullOrEmpty() && it.toyId == toyId }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(mToyConnectEvent: ToyConnectEvent) {
        // 只有当适配器不为null时，才进行处理
        toyAdapter?.let { adapter ->
            val index = toyList.indexOfFirst { it.toyId == mToyConnectEvent.id }
            if (index != -1) {
                toyList[index].status = mToyConnectEvent.connect
                adapter.notifyItemChanged(index)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    private fun requestPermissions() {
        RequestPermission.checkAndGrantedBluetoothPermission(this) {
            scanDev()
        }
    }
}
