package com.yutou.xboxcontrol

import android.app.PendingIntent
import android.content.Intent
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Bundle
import android.util.Log
import android.view.InputDevice
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.google.android.material.textview.MaterialTextView

class MainActivity : AppCompatActivity() {
    //通过插拔USB设备并打印UsbDevice.getProductId()和UsbDevice.getVendorId()获取小鸡手柄的设备ID，实际你们应该有一套手柄常见vid和pid吧
    val vid = 13623
    val pid = 4114
    lateinit var usbManager: UsbManager
    val ACTION_USB_PERMISSION: String = "com.example.usbcontrol.USB_PERMISSION"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        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
        }
        val textView=findViewById<MaterialTextView>(R.id.text)
        usbManager = getSystemService(USB_SERVICE) as UsbManager
        findViewById<Button>(R.id.button).setOnClickListener { _ ->
            run {
                textView.text="Wait"
                val sb=StringBuilder()
                usbManager.deviceList?.forEach { it ->
                    run {
                        Log.d("USB", "设备ID：${it.value.deviceName} , 设备vid:${it.value.vendorId} , 设备pid:${it.value.productId}")
                        sb.append("设备ID：${it.value.deviceName} , 设备vid:${it.value.vendorId} , 设备pid:${it.value.productId}\n")
                        if (it.value.productId == pid && it.value.vendorId == vid) {
                            requestPermission(it.value)
                        }
                    }
                }
                textView.text=sb.toString()
            }
        }
        findViewById<Button>(R.id.button2).setOnClickListener { _ ->
            run {
                textView.text="Wait"
                val deviceIds = InputDevice.getDeviceIds()
                val sb=StringBuilder()
                deviceIds.forEach { it->
                    run {
                        InputDevice.getDevice(it)?.let { device ->
                            run {
                                Log.e("USB", "设备ID：${device.id} , 设备vid:${device.vendorId} , 设备pid:${device.productId}")
                                sb.append("设备ID：${device.id} , 设备vid:${device.vendorId} , 设备pid:${device.productId}\n")
                            }
                        }
                    }
                }
                textView.text=sb.toString()

            }
        }
    }


    // 申请控制USB设备
    fun requestPermission(device: UsbDevice) {
        val permissionIntent = PendingIntent.getBroadcast(
            this,
            0,
            Intent(ACTION_USB_PERMISSION),
            PendingIntent.FLAG_IMMUTABLE
        )
        if (usbManager.hasPermission(device)) {
            connectUsb(device)
        } else {
            usbManager.requestPermission(device, permissionIntent)
        }
    }

    fun connectUsb(device: UsbDevice) {
        val connection = usbManager.openDevice(device)
        if (connection == null) {
            Log.e("USB", "连接失败")
            return
        }
        // 这里后续应该就是手柄协议之类的了，我不懂手柄协议，所以后续我就不写了
    }
}