package im.angry.openeuicc.core

import android.telephony.IccOpenLogicalChannelResponse
import android.telephony.TelephonyManager
import android.util.Log
import im.angry.openeuicc.util.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import net.typeblog.lpac_jni.ApduInterface

class TelephonyManagerApduInterface(
    private val port: UiccPortInfoCompat,
    private val tm: TelephonyManager,
    private val verboseLoggingFlow: Flow<Boolean>
): ApduInterface {
    companion object {
        const val TAG = "TelephonyManagerApduInterface"
    }

    override var valid: Boolean = false

    override fun connect() {
        // Do nothing
    }

    override fun disconnect() {
        // Do nothing
    }

    override fun logicalChannelOpen(aid: ByteArray): Int {
        val hex = aid.encodeHex()
        val channel = tm.iccOpenLogicalChannelByPortCompat(port.card.physicalSlotIndex, port.portIndex, hex, 0)
        if (channel.status != IccOpenLogicalChannelResponse.STATUS_NO_ERROR || channel.channel == IccOpenLogicalChannelResponse.INVALID_CHANNEL) {
            throw IllegalArgumentException("Cannot open logical channel $hex via TelephonManager on slot ${port.card.physicalSlotIndex} port ${port.portIndex}")
        }
        valid = true
        return channel.channel
    }

    override fun logicalChannelClose(handle: Int) {
        tm.iccCloseLogicalChannelByPortCompat(port.card.physicalSlotIndex, port.portIndex, handle)
        valid = false
    }

    override fun transmit(handle: Int, tx: ByteArray): ByteArray {
        if (runBlocking { verboseLoggingFlow.first() }) {
            Log.d(TAG, "TelephonyManager APDU: ${tx.encodeHex()}")
        }

        val cla = tx[0].toUByte().toInt()
        val ins = tx[1].toUByte().toInt()
        val p1 = tx[2].toUByte().toInt()
        val p2 = tx[3].toUByte().toInt()
        val p3 = tx[4].toUByte().toInt()
        val p4 = tx.drop(5).toByteArray().encodeHex()

        // @formatter:off
        val result = tm.iccTransmitApduLogicalChannelByPortCompat(
            port.card.physicalSlotIndex, port.portIndex, handle,
            cla, ins, p1, p2, p3, p4
        )
        // @formatter:on
        if (runBlocking { verboseLoggingFlow.first() })
            Log.d(TAG, "TelephonyManager APDU response: $result")
        return result?.decodeHex() ?: byteArrayOf()
    }
}