package com.mytatvarnsdk.activity

import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toDrawable
import androidx.core.graphics.toColorInt
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProviders
import cgmblelib.Enum.enumDevice
import cgmblelib.Enum.enumUnBind
import cgmblelib.ble.BleService
import cgmblelib.ble.gattcallback.GattTool
import cgmblelib.ble.gattcallback.ManageGattCallback
import cgmblelib.ble.reconnectManagament.ReconnectManagement
import cgmblelib.ble.scancallback.ManageScanCallback
import cgmblelib.custom.livedata.scan.PocDeviceAndRssi
import cgmblelib.database.entity.PocDevice
import cgmblelib.database.entity.PocGlucose
import com.bumptech.glide.Glide
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.CatalystInstance
import com.facebook.react.bridge.WritableMap
import com.facebook.react.modules.core.DeviceEventManagerModule
import com.mytatvarnsdk.CgmTrackyLibModule
import com.mytatvarnsdk.R
import com.mytatvarnsdk.base.BaseBleActivity
import com.mytatvarnsdk.databinding.ActivitySearchTransmitterBinding
import com.mytatvarnsdk.databinding.ExitDialogBottomsheetBinding
import com.mytatvarnsdk.model.GlucoseLog
import com.mytatvarnsdk.model.GlucoseLog.ErrorObject
import com.mytatvarnsdk.model.GlucoseLog.GlucoseStatusObject
import com.mytatvarnsdk.model.GlucoseLog.TrendObject
import com.mytatvarnsdk.model.MainActivityModel
import com.mytatvarnsdk.myView.dialog.DialogType
import com.mytatvarnsdk.myView.dialog.WarnDialogUtils
import com.mytatvarnsdk.myView.progress.ProgressManagement
import com.mytatvarnsdk.myView.progress.ProgressType
import com.mytatvarnsdk.network.AuthenticateSDKService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class SearchTransmitterActivity : BaseBleActivity() {
    private lateinit var binding: ActivitySearchTransmitterBinding
    private val handler = Handler(Looper.getMainLooper())
    private var isSearching = true
    private var isTransmitterConnected = false
    private var transmitterDeviceInfo: PocDeviceAndRssi? = null
    private lateinit var mModel: MainActivityModel
    lateinit var authenticateSDKService: AuthenticateSDKService
    private val job = Job()
    private val scope = CoroutineScope(Dispatchers.IO + job)
    private var isForReconnect: Boolean = false
    private val reactContext = CgmTrackyLibModule.mReactContext

    override fun init() {

    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySearchTransmitterBinding.inflate(layoutInflater)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        setupClickListeners()
        setupInitialState()
        startDeviceSearch()
    }

    override fun getPermission(): Array<out Array<out String?>?>? {
        return arrayOfNulls<Array<String?>>(0)
    }

    override fun onPermissionRequestSuccess() {
    }

    override fun onPermissionRequestFail(vararg permission: String?) {
    }

    override fun onPermissionRequestFailForever(vararg permission: String?) {
    }

    private fun setupInitialState() {
        sendDataToRN("", "cgm_connect_transmitter_landing")

        isForReconnect = intent.getBooleanExtra("IsForReconnect", false)

        // Set initial states
        binding.searchingLayout.visibility = View.VISIBLE
        binding.connectedLayout.visibility = View.GONE

        binding.commonButton.btnProceed.isEnabled = false
        binding.commonButton.btnProceed.alpha = 0.5f

        Glide.with(this)
            .asGif()
            .load(R.drawable.success_anim)
            .into(binding.ivSuccess)
    }

    fun manageErrorState(showError: Boolean, errorStatus: String) {
        if (showError) {
            binding.clFail.visibility = View.VISIBLE
            binding.clMain.visibility = View.GONE
            binding.commonButton.root.visibility = View.GONE

            Glide.with(this)
                .asGif()
                .load(R.drawable.warning)
                .into(binding.ivGif)

            binding.btnSupport.tvProceed.text = "Contact Support"
            binding.btnRetry.tvProceed.text = "Retry"

            binding.llWatchDemo.post {
                binding.llWatchDemo.setOnClickListener {
                    Log.d("CLICK", "Layout Clicked")
                    val intent = Intent(this, VideoActivity::class.java)
                    intent.putExtra("VideoId", "zRlFFdr-QD4")
                    startActivity(intent)
                }
            }

            binding.btnSupport.btnProceed.setOnClickListener {
                startActivity(
                    Intent(this, HelpActivity::class.java)
                        .putExtra("ScreenName", "Transmitter page")
                )
            }

            binding.btnRetry.btnProceed.setOnClickListener {
                sendDataToRN("", "cgm_retry_connect_transmitter_clicked")

                Handler().postDelayed({
                    val intent = intent
                    finish()
                    startActivity(intent)
                }, 500)
            }

            if (errorStatus.isNotEmpty()) {
                val jsonObject = JSONObject()
                jsonObject.put("error_description", errorStatus)
                sendDataToRN(jsonObject.toString(), "cgm_transmitter_connection_failed")

                binding.tvReason.visibility = View.VISIBLE
                binding.tvReason.text = "Reason - ${errorStatus}"
            } else {
                binding.tvReason.visibility = View.GONE
            }
        } else {
            binding.commonButton.root.visibility = View.VISIBLE
            binding.clFail.visibility = View.GONE
            binding.clMain.visibility = View.VISIBLE
        }
    }

    private fun openExitDialog() {
        val binding = ExitDialogBottomsheetBinding.inflate(layoutInflater)

        val dialog = Dialog(this)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(binding.root)

        val window = dialog.window
        window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        window?.setGravity(Gravity.BOTTOM)
        window?.setBackgroundDrawable(Color.TRANSPARENT.toDrawable())

        binding.btnExit.tvProceed.text = "Exit"

        binding.btnExit.root.setOnClickListener(View.OnClickListener { v: View? ->
            finish()
            dialog.dismiss()
        })

        binding.btnCancel.root.setOnClickListener(View.OnClickListener { v: View? ->
            dialog.dismiss()
        })

        binding.closeButton.setOnClickListener(View.OnClickListener { v: View? ->
            dialog.dismiss()
        })

        dialog.show()
    }


    public override fun scanStart() {
        if (mPocDevice != null && mPocDevice.isBound) {
            ProgressManagement.getInstance().showWait(this, ProgressType.PROGRESSDIALOG_SCAN, null)
        }
        manageErrorState(false, "")
    }


    public override fun scanIn(device: PocDeviceAndRssi) {
        transmitterDeviceInfo = device
        if (isSearching) {
            deviceDetected(device)
        }
        manageErrorState(false, "")
    }

    public override fun scanEnd() {
        if (transmitterDeviceInfo != null && !binding.tvReason.isVisible) {
            manageErrorState(false, "")
        } else {
            sendDataToRN("", "cgm_transmitter_detection_failed")
            manageErrorState(true, "Timeout")
        }
        Log.d("Search Transmitter Error--> ", "Search Transmitter Error--> scanEnd")
    }

    override fun bluetoothStateOFF() {
        super.bluetoothStateOFF()

        manageErrorState(true, "Bluetooth Off")
        Log.d("Search Transmitter Error--> ", "Search Transmitter Error--> bluetoothStateOFF")
    }

    override fun failGPS() {
        super.failGPS()
        manageErrorState(true, "GPS Off")
        Log.d("Search Transmitter Error--> ", "Search Transmitter Error--> failGPS")
    }

    override fun failLocal() {
        super.failLocal()
        manageErrorState(true, "Something went wrong")
        Log.d("Search Transmitter Error--> ", "Search Transmitter Error--> failLocal")
    }

    public override fun bindFail() {
        ProgressManagement.getInstance().dismissWait(this)
        manageErrorState(true, "Bind Failure")
        Log.d("Search Transmitter Error--> ", "Search Transmitter Error--> bindFail")
        sendDataToRN("", "cgm_transmitter_connection_failed")
    }

    public override fun bindSuccess() {
        ProgressManagement.getInstance().dismissWait(this)

        binding.tvTransName.text = "Sno: ${transmitterDeviceInfo!!.pocDevice.name}"
        val formatter = SimpleDateFormat("hh:mm a", Locale.getDefault())
        binding.tvDateTime.text = "Connected on ${formatter.format(Date()).uppercase()}"
        binding.clMain.visibility = View.GONE
        binding.clSuccess.visibility = View.VISIBLE
        binding.commonButton.btnProceed.isEnabled = true
        binding.commonButton.btnProceed.alpha = 1.0f
        binding.view2.background = ContextCompat.getDrawable(this, R.drawable.bg_green_progress)
        binding.tvDivide2.setTextColor("#299D6B".toColorInt())

        sendDataToRN("", "cgm_transmitter_connection_successful")
    }


    public override fun disconnect() {
        ProgressManagement.getInstance().dismissWait(this)
        showShortToast(R.string.bt_connect_fail)
        manageErrorState(true, "Disconnected")
    }

    public override fun disconnectForTimeout() {
        ProgressManagement.getInstance().dismissWait(this)
        manageErrorState(true, "Disconnected")
        Log.d("Search Transmitter Error--> ", "Search Transmitter Error--> disconnectForTimeout")
    }

    public override fun checkFailForLowPower() {
        ProgressManagement.getInstance().dismissWait(this)
        WarnDialogUtils.getInstance().showWarnDialog(this, DialogType.TYPE_LOW_POWER)
    }

    public override fun checkFailErrorTemperature() {
        ProgressManagement.getInstance().dismissWait(this)
    }

    public override fun onlineLost() {
        showShortToast(R.string.online_lost)
    }


    private fun bind(device: PocDevice) {
        try {
            if (device.address != null) {
                ManageGattCallback.getInstance().ConnectViaAddress(device.address)
                ManageScanCallback.getInstance().stopLeScan()
                ProgressManagement.getInstance()
                    .showWait(this, ProgressType.PROGRESSDIALOG_CONNECT, null)
            }
        } catch (e: Exception) {
            Log.d("bind::-> ", "bind: ${e.message}")
        }
    }

    private fun setupClickListeners() {
        binding.toolbar.btnWhatsapp.setOnClickListener {
            startActivity(
                Intent(this, HelpActivity::class.java)
                    .putExtra("ScreenName", "Transmitter page")
            )
        }

        binding.toolbar.btnWatchDemo.setOnClickListener {
            sendDataToRN("", "cgm_watch_demo_clicked")

            startActivity(
                Intent(this, VideoActivity::class.java).putExtra("VideoId", if (isForReconnect) "n_pUrFoZ1wQ" else "r5Zemc4R044")
            )
        }

        binding.toolbar.btnClose.setOnClickListener {
            openExitDialog()
        }

        // Connect button (visible when device is detected)
        binding.btnConnect.setOnClickListener {
            connectToTransmitter()
        }

        val callback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                openExitDialog()
            }
        }
        onBackPressedDispatcher.addCallback(this, callback)

        binding.commonButton.btnProceed.setOnClickListener {
//      CoroutineScope(Dispatchers.IO).launch {
//        // This block runs in IO thread
//        val result = mModel.glucoseByTime
//
//        // If you want to update UI, switch to Main thread
//        withContext(Dispatchers.Main) {
//          val transformedLogs = result.map {
//            CgmLog(
//              timeInMillis = it.timeInMillis,
//              countdownMinutes = it.countdownMinutes,
//              countdownDays = it.countdownDays,
//              hypoglycemiaEarlyWarnMinutes = it.hypoglycemiaEarlyWarnMinutes,
//              showGlucoseMG = it.showGlucoseMG,
//              glucoseId = it.glucoseId,
//              name = it.name,
//              bytes = it.bytes,
//              showGlucose = it.showGlucose,
//              Ib = it.ib,
//              Iw = it.iw,
//              countdownHours = it.countdownHours,
//              T = it.t,
//              year = it.year,
//              month = it.month,
//              day = it.day,
//              hour = it.hour,
//              minute = it.minute,
//              trendObject = TrendObject(
//                trendId = it.trend.trendId,
//                drawableId = it.trend.drawableId,
//                widgetImg = it.trend.widgetImg,
//                apsChangeRate = it.trend.apsChangeRate
//              ),
//              glucoseStatusObject = GlucoseStatusObject(
//                statusId = it.glucoseStatus.statusId
//              ),
//              errorObject = ErrorObject(
//                errorId = it.errorCode.errorId,
//                sound = it.errorCode.sound
//              )
//            )
//          }
//
//          val allResult = AllCGMLogRequest(
//            vendor = "GoodFlip",
//            logs = transformedLogs
//          )
//
//          val json = Gson().toJson(allResult)
//          logLongJson("Final JSON=>>> ", json)
//
//


////          authenticateSDKService.postCGMData(
////            environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
////            data = json.toString(),
////            token = "ILtFcw+xtbuy8IgsBCSyD6nSpgZd5AOz7T+g3N8Tef/INZi+dxwPJhnBc2kfdq2ep15mSq5R4US0zEmZlLhiQoxyibxttJilEA2YyknRcw+OooxMSq3pHcUs04r+VUk0Yg1LBmqz1XmmVgJVNvFnMYVTD0NQ/eK8wihua23MnmWeb5MsNjfMxJRlxfHxNnACuEWHOxjJ+hw/obw4mF9ESWHyw/ZX4V3fZ8IpC7aKYpBlxVT0c4PmLX/ESYWG3y+5OaCa5MvtOsH1ueRXpMN3tg+kq/w5NQloyVZcsvn34Y8mhaE7kb4Ze396jvek05lJBO+gN1FLG3YdSLNkTBsbAjIwVR2XLac3jj2p+JcH7RVlnqkFJNkoYYwj5g7gi1eYo0jrYBmrJBjBtAMjtK1rv8N+TWaTl5RuNEMc08u18HgFy/squ7qzBMnQ9vz9xD1b1lr3T9JwWgwt+/B26omz1uO2ao/GcFSSEsWZHJWDxvXAZ7nCadCg9oNc5c0f85Ug7+EFcMnIKk1IpmHiAQueppEArY6K7I2Bif2uVEWyxWFbbPB3YlXdEdGugzLkJGFJE7zuw83oHNNZWMHu8EpoUf7Gpi6Jp09XRT6zc9ibwp7JAleQdKWoXr0P/WxzK9FWEUtRbxkjWsltNpjOCAtFs8Gqf6jOrERUwXylBnwuGG1Tv91jCpn2ywe1GW71fsSCjkPHewXvI+BMdunuwK+rbTKJNCi4oX9B69WP/8yznAqu6ylJSCu0gJKOng0xBjuQi0Dxdgmfo9jJPRKS7dNVzNCgmTqUD7b3baKxAGgq6mUjXtJsP/8QaEtkt60HvmXeTcKzIqTBmE0t98fZ48k4WJ2RCrqpRgPF+U0rlmvkojGeLGw76Xf9EXFrz8OuIHKlqjB3NxfnnDB8k/fcuiVhQ3CGnJfNKSN6EBDpO7fMD8KL9B9g/78arwFAzA4GdZryTwJyOOCUsdHZessHu0hGtRkh9cyJyD7VP2wPXJ3BmgKGSqHYiFAQv50pEbHaxC3QT9qlH3PTGMJpaLXT96+N72+axfWH61Qa/tSmzcJcOf9IivJMQmax2DVUroRQHYeVbzzzQFuT/xkdR4eIJGplMBjrzCMMWKxTsEXqB3DIrP1l6zlj6hoOVJtfib+5VRNGeO9TAf8R/ALZMyIjCwqTPvC7h/5qQnT7SGVX0eTz48iwprn5otn3mZ6rQERNZtpGQapdmyMroKP0Ckuu5+qsCxKvvrMD6RnDLSR9xgvk8wRJFCYTQN52vmrZnz4QQYHHZAFwT2nTRoUx49dk9D+O/gBCXEkwPU6ar0lQc0zOgFrw7itEVSmhc3D8vZtLiW6HRGzKCxVBbnN0o1wUm+2Wu/KCEDOnJbC4ui/FXyFpaM6A9N4RfLmwAegN0ZSp9YeH"
////          )
//
////          val glucoseJson: String? = Gson().toJson(result)
////
////          val dto: GlucoseLog = mapToDto(pocGlucose)
////
////          val request: GlucoseLogRequest = GlucoseLogRequest(vendor = "GoodFlip", logs = logs)
////          val gson: Gson = GsonBuilder().create()
////          val json = gson.toJson(request)
////
////          Log.d("Glucose data 3 min==> ", "glucoseJson: $glucoseJson")
////
////          Log.d("Glucose data 3 min==> ", "final Json: $json")
////
////          authenticateSDKService.postCGMData(
////            environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
////            data = json.toString(),
////            token = "ILtFcw+xtbuy8IgsBCSyD6nSpgZd5AOz7T+g3N8Tef/INZi+dxwPJhnBc2kfdq2ep15mSq5R4US0zEmZlLhiQoxyibxttJilEA2YyknRcw+OooxMSq3pHcUs04r+VUk0Yg1LBmqz1XmmVgJVNvFnMYVTD0NQ/eK8wihua23MnmWeb5MsNjfMxJRlxfHxNnACuEWHOxjJ+hw/obw4mF9ESWHyw/ZX4V3fZ8IpC7aKYpBlxVT0c4PmLX/ESYWG3y+5OaCa5MvtOsH1ueRXpMN3tg+kq/w5NQloyVZcsvn34Y8mhaE7kb4Ze396jvek05lJBO+gN1FLG3YdSLNkTBsbAjIwVR2XLac3jj2p+JcH7RVlnqkFJNkoYYwj5g7gi1eYo0jrYBmrJBjBtAMjtK1rv8N+TWaTl5RuNEMc08u18HgFy/squ7qzBMnQ9vz9xD1b1lr3T9JwWgwt+/B26omz1uO2ao/GcFSSEsWZHJWDxvXAZ7nCadCg9oNc5c0f85Ug7+EFcMnIKk1IpmHiAQueppEArY6K7I2Bif2uVEWyxWFbbPB3YlXdEdGugzLkJGFJE7zuw83oHNNZWMHu8EpoUf7Gpi6Jp09XRT6zc9ibwp7JAleQdKWoXr0P/WxzK9FWEUtRbxkjWsltNpjOCAtFs8Gqf6jOrERUwXylBnwuGG1Tv91jCpn2ywe1GW71fsSCjkPHewXvI+BMdunuwK+rbTKJNCi4oX9B69WP/8yznAqu6ylJSCu0gJKOng0xBjuQi0Dxdgmfo9jJPRKS7dNVzNCgmTqUD7b3baKxAGgq6mUjXtJsP/8QaEtkt60HvmXeTcKzIqTBmE0t98fZ48k4WJ2RCrqpRgPF+U0rlmvkojGeLGw76Xf9EXFrz8OuIHKlqjB3NxfnnDB8k/fcuiVhQ3CGnJfNKSN6EBDpO7fMD8KL9B9g/78arwFAzA4GdZryTwJyOOCUsdHZessHu0hGtRkh9cyJyD7VP2wPXJ3BmgKGSqHYiFAQv50pEbHaxC3QT9qlH3PTGMJpaLXT96+N72+axfWH61Qa/tSmzcJcOf9IivJMQmax2DVUroRQHYeVbzzzQFuT/xkdR4eIJGplMBjrzCMMWKxTsEXqB3DIrP1l6zlj6hoOVJtfib+5VRNGeO9TAf8R/ALZMyIjCwqTPvC7h/5qQnT7SGVX0eTz48iwprn5otn3mZ6rQERNZtpGQapdmyMroKP0Ckuu5+qsCxKvvrMD6RnDLSR9xgvk8wRJFCYTQN52vmrZnz4QQYHHZAFwT2nTRoUx49dk9D+O/gBCXEkwPU6ar0lQc0zOgFrw7itEVSmhc3D8vZtLiW6HRGzKCxVBbnN0o1wUm+2Wu/KCEDOnJbC4ui/FXyFpaM6A9N4RfLmwAegN0ZSp9YeH"
////          )
//        }
//      }

            if (isTransmitterConnected) {
                proceedToNextStep()
            }
        }
    }

    private fun sendDataToRN(data: String, status: String) {
        if (reactContext != null) {
            try {
                val catalystInstance: CatalystInstance = reactContext.catalystInstance
                val module = catalystInstance.getNativeModule(CgmTrackyLibModule::class.java)

                if (module == null) {
                    sendDataToRNDirectly(data, status)
                    Log.d("sendDataToRN: ", "Module null")
                } else {
                    module.sendDataToReact(data, status, "cgmDeviceEvent")
                    Log.d("sendDataToRN: ", "Module is not null")
                }
            } catch (e: Exception) {
                Log.e("sendDataToRN: Error ", e.message.toString())
            }
        } else {
            Log.e("TrackyActivity", "ReactApplicationContext is null")
        }
    }


    private fun sendDataToRNDirectly(data: String, status: String) {
        try {
            val map: WritableMap = Arguments.createMap().apply {
                putString("data", data)
                putString("status", status)
            }

            reactContext?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
                ?.emit("cgmDeviceEvent", map)
        } catch (e: Exception) {
            Log.e("sendDataToRNDirectly", "Error sending data to React", e)
        }
    }

    fun logLongJson(tag: String, message: String) {
        val maxLogSize = 4000
        for (i in 0..message.length / maxLogSize) {
            val start = i * maxLogSize
            val end = (i + 1) * maxLogSize
            if (start < message.length) {
                Log.d(tag, message.substring(start, minOf(end, message.length)))
            }
        }
    }

    private fun startDeviceSearch() {
        mModel = ViewModelProviders.of(this)[MainActivityModel::class.java]

        ReconnectManagement.getInstance()
            .reconnect(ReconnectManagement.ReconnectState.STATE_SCAN_AGAIN)

        authenticateSDKService = AuthenticateSDKService(scope = scope)

        isSearching = true
        isTransmitterConnected = false

        // Show searching state
        binding.searchingLayout.visibility = View.VISIBLE
        binding.connectedLayout.visibility = View.GONE

        Glide.with(this)
            .asGif()
            .load(R.drawable.searching)
            .into(binding.progressSearch)

        binding.commonButton.btnProceed.isEnabled = false
        binding.commonButton.btnProceed.alpha = 0.5f
    }

    private fun deviceDetected(device: PocDeviceAndRssi) {
        isSearching = false

        // Animate the transition
        val fadeOut = AlphaAnimation(1.0f, 0.0f)
        fadeOut.duration = 300
        fadeOut.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation?) {}

            override fun onAnimationEnd(animation: Animation?) {
                binding.searchingLayout.visibility = View.GONE

                // Show the connected layout
                binding.connectedLayout.visibility = View.VISIBLE
                binding.tvSerialNumber.text = device.pocDevice.name

                // Fade in the connected layout
                val fadeIn = AlphaAnimation(0.0f, 1.0f)
                fadeIn.duration = 300
                binding.connectedLayout.startAnimation(fadeIn)
            }

            override fun onAnimationRepeat(animation: Animation?) {}
        })

        binding.searchingLayout.startAnimation(fadeOut)

        sendDataToRN("", "cgm_transmitter_detected")
    }

    private fun connectToTransmitter() {
        isTransmitterConnected = true

        if (transmitterDeviceInfo != null) {
            if (isForReconnect) {
                GattTool.unBindInDatabase(this, enumUnBind.UNBIND_FORCE)
            }

            Log.d("onDeviceConnect--->", "onDeviceConnect: " + transmitterDeviceInfo.toString())
            if (enumDevice.getEnumDevice(transmitterDeviceInfo!!.pocDevice.name).isAbleScanQRCode) {
                bindSuccess()
            } else {
                bind(transmitterDeviceInfo!!.pocDevice)
            }
        }
    }

    private fun proceedToNextStep() {
        val intent = Intent(this, ConnectSensorActivity::class.java)
        intent.putExtra("transmitterDeviceInfo", transmitterDeviceInfo)
        intent.putExtra("IsForReconnect", isForReconnect)
        startActivity(intent)
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }

    override fun onResume() {
        super.onResume()
        BleService.startService(this)
    }

    override fun setView(): Int {
        return R.layout.activity_search_transmitter
    }

    override fun initViews() {
    }

    override fun onClick(p0: View?) {
    }


}
