package com.dlc.eboard.ui.settings

import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import com.dlc.eboard.R
import com.dlc.eboard.databinding.ActivitySettingsScanBinding
import com.dlc.eboard.sp.PortDevicesSp
import com.rc.core.ui.activity.RcBaseActivity
import eyecool_serialport_api.SerialPortFinder

/**
 * info
 *
 * @author ReiChin_
 */
class ScanSettingsActivity :
    RcBaseActivity<ActivitySettingsScanBinding>() {

    override fun createViewBinding() = ActivitySettingsScanBinding.inflate(layoutInflater)

    override fun initViews(savedInstanceState: Bundle?) {
        viewBinding.back.setOnClickListener {
            finish()
        }

        // 串口号
        viewBinding.path.setOnClickListener {
            val items = SerialPortFinder().allDevicesPath
            AlertDialog.Builder(this)
                .setTitle("选择串口号")
                .setItems(items) { _, which ->
                    viewBinding.path.text = items[which]
                }.show()
        }

        // 波特率
        viewBinding.baudRate.setOnClickListener {
            val items = resources.getTextArray(R.array.baud_rates)
            AlertDialog.Builder(this)
                .setTitle("选择波特率")
                .setItems(items) { _, which ->
                    viewBinding.baudRate.text = items[which]
                }.show()
        }

        // 确定
        viewBinding.confirm.setOnClickListener {
            PortDevicesSp.saveConfig(
                context = this,
                path = viewBinding.path.text.toString(),
                baudRate = viewBinding.baudRate.text.toString().toInt()
            )
            viewBinding.confirm.postDelayed({
                setResult(RESULT_OK)
                finish()
            }, 50)
        }
    }

    override fun initData() {
        val device = PortDevicesSp.loadConfig(this)
        viewBinding.path.text = device.path
        viewBinding.baudRate.text = device.baudRate.toString()
    }

}