// Adapted from <https://github.com/open-keychain/open-keychain/blob/master/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/securitytoken/usb>
package im.angry.openeuicc.core.usb

import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface

class UsbTransportException(message: String) : Exception(message)

val UsbDevice.interfaces: Iterable<UsbInterface>
    get() = (0 until interfaceCount).map(::getInterface)

val UsbInterface.endpoints: Iterable<UsbEndpoint>
    get() = (0 until endpointCount).map(::getEndpoint)

fun UsbInterface.getIoEndpoints(): Pair<UsbEndpoint?, UsbEndpoint?> {
    val endpoints = endpoints
        .filter { it.type == UsbConstants.USB_ENDPOINT_XFER_BULK }
    return Pair(
        endpoints.first { it.direction == UsbConstants.USB_DIR_IN },
        endpoints.first { it.direction == UsbConstants.USB_DIR_OUT },
    )
}

fun UsbDevice.getSmartCardInterface() =
    interfaces.first { it.interfaceClass == UsbConstants.USB_CLASS_CSCID }