package com.dlc.eboard.ui.settings

import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.provider.Settings
import androidx.appcompat.app.AlertDialog
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.common.Constants
import com.dlc.eboard.databinding.ActivitySettingsBinding
import com.dlc.eboard.sp.EnvConfig
import com.dlc.eboard.sp.EnvSp
import com.dlc.eboard.sp.PortDevicesSp
import com.dlc.eboard.ui.SplashActivity
import com.rc.core.ui.ActivityCollector
import com.rc.core.ui.activity.RcBaseActivity
import com.rc.core.util.DeviceUtils
import com.rc.httpcore.HttpConfig
import java.lang.ref.WeakReference
import java.util.*

/**
 * info
 *
 * @author ReiChin_
 */
class SettingsActivity : RcBaseActivity<ActivitySettingsBinding>() {

    companion object {
        private const val REQ_SCAN = 101
    }
    private val weakHandler by lazy { WeakReferenceHandler(this) }
    override fun createViewBinding() = ActivitySettingsBinding.inflate(layoutInflater)

    override fun initListener() {
        viewBinding.back.setOnClickListener {
            ActivityCollector.finishAll()
            val intent = Intent(this, SplashActivity::class.java)
            startActivity(intent)
        }

        viewBinding.versionInfoLayout.setOnLongClickListener {
            startActivity(Intent(Settings.ACTION_SETTINGS))
            finish()
            true
        }

        viewBinding.apiVersion.setOnClickListener {
            val items = HttpConfig.ApiVersion.values().map { it.desc }.toTypedArray()
            val apiVersion = viewBinding.apiVersion.tag as Int? ?: Constants.NetExtra.API_VERSION
            AlertDialog.Builder(this)
                .setTitle("选择Api版本")
                .setSingleChoiceItems(items, apiVersion) { dialog, which ->
                    viewBinding.apiVersion.tag = which
                    viewBinding.apiVersion.text = items[which]
                    dialog.dismiss()
                }.show()
        }

        // 扫描抢
        viewBinding.scan.setOnClickListener {
            val intent = Intent(this, ScanSettingsActivity::class.java)
            startActivityForResult(intent, REQ_SCAN)
        }

        viewBinding.confirm.setOnClickListener { changeEen() }
    }

    private fun changeEen() {
        val inputEnv = viewBinding.curEnvInput.text.toString().trim()
        if (inputEnv.isEmpty()) {
            showToast("服务器新环境不能为空！")
            return
        }

        val inputSafetyEnv = viewBinding.curEnvSafetyInput.text.toString().trim()
        if (inputSafetyEnv.isEmpty()) {
            showToast("安全准入检测新环境不能为空！")
            return
        }

        val mqttInputEnv = viewBinding.curMqttEnvInput.text.toString().trim()
        if (mqttInputEnv.isEmpty()) {
            showToast("MQTT新环境不能为空！")
            return
        }

        val mqttInputName = viewBinding.curMqttNameInput.text.toString().trim()
        if (mqttInputName.isEmpty()) {
            showToast("MQTT账号不能为空！")
            return
        }

        val mqttInputPwd = viewBinding.curMqttPwdInput.text.toString().trim()
        if (mqttInputPwd.isEmpty()) {
            showToast("MQTT密码不能为空！")
            return
        }

        val settingPwd = viewBinding.curSettingPwdInput.text.toString().trim()
        if (settingPwd.isEmpty()) {
            showToast("工程模式密码不能为空！")
            return
        }

        val apiVersion = viewBinding.apiVersion.tag as Int? ?: Constants.NetExtra.API_VERSION

        val newEnv = if (!inputEnv.endsWith("/")) "${inputEnv}/" else inputEnv
        val newSafetyEnv =
            if (!inputSafetyEnv.endsWith("/")) "${inputSafetyEnv}/" else inputSafetyEnv
        val envConfig = EnvConfig(newEnv, newSafetyEnv, mqttInputEnv, mqttInputName, mqttInputPwd, settingPwd, apiVersion)
        EnvSp.saveEnv(this, envConfig)
        weakHandler.sendEmptyMessageDelayed(1, 1500)
//        object : Handler(Looper.getMainLooper()) {
//            override fun handleMessage(msg: Message) {
//                CommonUtils.restartApp(applicationContext)
//            }
//        }.sendEmptyMessageDelayed(1, 1000)
    }

    override fun initData() {
        viewBinding.androidId.text = CommonUtils.getAndroidId()
        viewBinding.versionName.text = DeviceUtils.getVersionName(this)
        viewBinding.curEnv.text = HttpConfig.API_BASE_URL
        viewBinding.curSafetyEnv.text = HttpConfig.SIGN_IN_CHECK_BASE_URL

        val apiVersion = EnvSp.loadEnv(this)?.apiVersion ?: Constants.NetExtra.API_VERSION
        viewBinding.apiVersion.text = HttpConfig.ApiVersion.values().find { it.code == apiVersion }?.desc
        viewBinding.apiVersion.tag = apiVersion

        viewBinding.curMqttEnv.text = Constants.MqttConfig.SERVER_URI
        viewBinding.curMqttName.text = Constants.MqttConfig.U_NAME
        viewBinding.curMqttPwd.text = Constants.MqttConfig.U_PWD

        viewBinding.curSettingPwd.text = EnvSp.loadEnv(this)?.settingPwd ?: Constants.Mock.SETTING_PWD

        loadScanConfig()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQ_SCAN -> if (RESULT_OK == resultCode) loadScanConfig()
        }
    }

    private fun loadScanConfig() {
        val device = PortDevicesSp.loadConfig(this)
        viewBinding.scan.text =
            String.format(Locale.US, "path %s, baud rate %d", device.path, device.baudRate)
    }
    // static + 弱引用  防止内存泄露
    class WeakReferenceHandler(obj: SettingsActivity) : Handler(Looper.getMainLooper()) {
        private val mRef: WeakReference<SettingsActivity> = WeakReference(obj)

        override fun handleMessage(msg: Message) {
            mRef.get()?.run {
                CommonUtils.restartApp(this)
            }
        }
    }

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