package com.dlc.chemical.print

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.util.Log
import com.print.usbprint.util.USBUtil
import org.greenrobot.eventbus.EventBus
import java.io.IOException

/**
 * USB 设备监听广播
 *
 * @author ReiChin_
 */
class UsbReceiver : BroadcastReceiver() {

    companion object {
        private const val TAG = "ReiChin_USBReceiver"

        const val ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"
        const val ACTION_USB_STATE = "android.hardware.usb.action.USB_STATE"
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        when (intent?.action) {
            ACTION_USB_PERMISSION -> {
                // 获取权限结果的广播
                synchronized(this) {
                    val device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as? UsbDevice
                    device?.let {
                        //call method to set up device communication
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            Log.i(TAG, "USBReceiver获取权限成功：${it.deviceName}")
                            EventBus.getDefault().post(UsbDeviceEvent(it))
                        } else {
                            Log.e(TAG, "USBReceiver获取权限失败：${it.deviceName}")
                        }
                    }
                }
            }

            UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
                // 有新的设备插入了，在这里一般会判断这个设备是不是我们想要的，是的话就去请求权限
                Log.i(TAG, "USBReceiver检测到：usb插入")
                val device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as? UsbDevice
                device?.let { getUsbPermission(it, context) }
            }

            UsbManager.ACTION_USB_DEVICE_DETACHED -> {
                // 有设备拔出了
                Log.i(TAG, "USBReceiver检测到：usb拔出")
            }
            ACTION_USB_STATE -> {
                // 已经有usb设备连接
                Log.i(TAG, "USBReceiver检测到：action=${ACTION_USB_STATE}")
                try {
                    context?.let { getDetail(it) }
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

    private lateinit var mUsbManager: UsbManager

    private fun getUsbPermission(usbDevice: UsbDevice, context: Context?) {
        context?.let {
            val pendingIntent = PendingIntent.getBroadcast(it, 0, Intent(ACTION_USB_PERMISSION), 0)
            USBUtil.getInstance().init(it)
            mUsbManager = USBUtil.getInstance().usbManager
            USBUtil.getInstance().usbManager = mUsbManager
            mUsbManager.requestPermission(usbDevice, pendingIntent)
        }
    }

    private fun getDetail(context: Context) {
        val usbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
        USBUtil.getInstance().usbManager = usbManager
        val deviceIterator: Iterator<UsbDevice> = usbManager.deviceList.values.iterator()
        while (deviceIterator.hasNext()) {
            val device = deviceIterator.next()
            val pendingIntent =
                PendingIntent.getBroadcast(context, 0, Intent(ACTION_USB_PERMISSION), 0)
            usbManager.requestPermission(device, pendingIntent)
            device.toString()
            Log.i(TAG, "UseDeviceDetail: $device")
        }
    }

}