package com.posprinter.printdemo.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.appcompat.app.AppCompatActivity
import com.jeremyliao.liveeventbus.LiveEventBus
import com.posprinter.printdemo.App
import com.posprinter.printdemo.R
import com.posprinter.printdemo.databinding.ActivityFirstBinding
import com.posprinter.printdemo.utils.Constant
import com.posprinter.printdemo.utils.UIUtils
import com.posprinter.printdemo.widget.DlgUsbSelect
import net.posprinter.POSConnect

class MainActivity : AppCompatActivity() {
    private lateinit var bind: ActivityFirstBinding
    private var pos = 0
    private val launcher = registerForActivityResult(StartActivityForResult()) { result: ActivityResult ->
        if (result.resultCode == RESULT_OK) {
            val mac = result.data!!.getStringExtra(SelectBluetoothActivity.INTENT_MAC)
            bind.addressTv.text = mac
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bind = ActivityFirstBinding.inflate(layoutInflater)
        setContentView(bind.root)
        initListener()
        val entries = POSConnect.getSerialPort()
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, entries)
        bind.serialPortNs.adapter = adapter
        LiveEventBus.get<Boolean>(Constant.EVENT_CONNECT_STATUS).observeForever {
            refreshButton(it)
        }
    }

    private fun initListener() {
        bind.buttonConnect.setOnClickListener {
            refreshButton(false)
            when (pos) {
                0 -> connectUSB()
                1 -> connectNet()
                2 -> connectBt()
                3 -> {
                    if (bind.serialPortNs.selectedItem == null) {
                        UIUtils.toast(R.string.cannot_find_serial)
                    } else {
                        connectSerial(bind.serialPortNs.selectedItem.toString(), bind.baudRateNs.selectedItem.toString())
                    }
                }
            }
        }
        bind.buttonDisconnect.setOnClickListener {
            refreshButton(false)
            App.get().curConnect?.close()
        }
        bind.buttonpos.setOnClickListener {
            if (App.get().curConnect?.isConnect == true) {
                val intent = Intent(this, PosActivity::class.java)
                startActivity(intent)
            } else {
                UIUtils.toast(R.string.connect_first)
            }
        }

        bind.addressTv.setOnClickListener {
            when (pos) {
                2 -> launcher.launch(Intent(this, SelectBluetoothActivity::class.java))
                0 -> DlgUsbSelect(this, POSConnect.getUsbDevices(this)) { s ->
                    bind.addressTv.text = s
                }.show()
            }
        }
        bind.portSp.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(adapterView: AdapterView<*>?, view: View, i: Int, l: Long) {
                pos = i
                when (i) {
                    1 -> {
                        bind.baudRateNs.visibility = View.GONE
                        bind.serialPortNs.visibility = View.GONE
                        bind.addressEt.visibility = View.VISIBLE
                        bind.addressTv.visibility = View.GONE
                    }
                    0, 2 -> {
                        bind.baudRateNs.visibility = View.GONE
                        bind.serialPortNs.visibility = View.GONE
                        bind.addressEt.visibility = View.GONE
                        bind.addressTv.visibility = View.VISIBLE
                        if (pos == 2) {
                            bind.addressTv.text = ""
                        } else {
                            searchUsb()
                        }
                    }
                    3 -> {
                        bind.addressEt.visibility = View.GONE
                        bind.addressTv.visibility = View.GONE
                        bind.baudRateNs.visibility = View.VISIBLE
                        bind.serialPortNs.visibility = View.VISIBLE
                    }
                }
            }

            override fun onNothingSelected(adapterView: AdapterView<*>?) {}
        }
    }

    private fun refreshButton(connect: Boolean) {
        bind.buttonDisconnect.isEnabled = connect
        bind.buttonpos.isEnabled = connect
    }

    //net connection
    private fun connectNet() {
        val ipAddress = bind.addressEt.text.toString()
        if (ipAddress == "") {
            UIUtils.toast(R.string.none_ipaddress)
        } else {
            App.get().connectNet(ipAddress)
        }
    }

    //USB connection
    private fun connectUSB() {
        val usbAddress = bind.addressTv.text.toString()
        if (usbAddress == "") {
            UIUtils.toast(R.string.usb_select)
        } else {
            App.get().connectUSB(usbAddress)
        }
    }

    //bluetooth connection
    private fun connectBt() {
        val bleAddress = bind.addressTv.text.toString()
        if (bleAddress == "") {
            UIUtils.toast(R.string.bt_select)
        } else {
            App.get().connectBt(bleAddress)
        }
    }

    private fun connectSerial(port: String, boudrate: String) {
        App.get().connectSerial(port, boudrate)
    }

    private fun searchUsb(): String {
        val usbNames = POSConnect.getUsbDevices(this)
        var ret = ""
        if (usbNames.isNotEmpty()) {
            ret = usbNames[0]
        }
        bind.addressTv.text = ret
        return ret
    }

    override fun onDestroy() {
        super.onDestroy()
        App.get().curConnect?.close()
    }
}