package com.example.defenseapplication.home

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.defenseapplication.bean.AddDeviceBean
import com.example.defenseapplication.bean.DeviceBean
import com.example.defenseapplication.databinding.SetNameActivityBinding
import com.example.defenseapplication.liveVideo.LiveVideoActivity
import com.example.defenseapplication.utils.RetrofitNetwork
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SetNameActivity : AppCompatActivity() {

    private lateinit var binding: SetNameActivityBinding
    private var wifiName: String = ""
    private var wifiPassword: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = SetNameActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topBar)
            .init()
        
        // 获取传递的 WiFi 名称和密码
        wifiName = intent.getStringExtra("wifi_name") ?: ""
        wifiPassword = intent.getStringExtra("wifi_password") ?: ""
        
        binding.ivBack.setOnClickListener {
            finish()
        }
        
        binding.btnConfirm.setOnClickListener {
            val deviceName = binding.etName.text.toString().trim()
            if (deviceName.isEmpty()) {
                Toast.makeText(this, "请输入设备名称", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            addDevice(deviceName)
        }
    }
    
    private fun addDevice(deviceName: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val deviceBean = AddDeviceBean(
                    deviceName = deviceName,
                    wifiName = wifiName,
                    wifiPassword = wifiPassword,
                    status = "0"
                )
                val result = RetrofitNetwork.getNetworkService().addDevice(deviceBean)
                withContext(Dispatchers.Main) {
                    if (result.code == 200) {
                        Toast.makeText(this@SetNameActivity, "设备添加成功", Toast.LENGTH_SHORT).show()
                        startActivity(Intent(this@SetNameActivity, LiveVideoActivity::class.java))
                        finish()
                    } else {
                        Toast.makeText(this@SetNameActivity, result.msg ?: "添加失败", Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@SetNameActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}