package com.lemonhc.mplus.mcare_plus.activity.nfc

import android.nfc.NdefRecord
import android.nfc.Tag
import android.nfc.tech.Ndef
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.UnsupportedEncodingException
import java.util.*
import kotlin.experimental.and

class NdefReaderTask(val tag: Tag, val handler:(String) -> Unit){
    fun execute(){
        CoroutineScope(Dispatchers.Default).launch {
            val ndef = Ndef.get(tag)
            val ndefMessage = ndef.cachedNdefMessage

            val records = ndefMessage.records
            for (ndefRecord in records) {
                if (ndefRecord.tnf == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.type, NdefRecord.RTD_TEXT)) {
                    try {
                        val text = readText(ndefRecord)
                        handler(text)
                    } catch (e: UnsupportedEncodingException) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }

    @Throws(UnsupportedEncodingException::class)
    private fun readText(record: NdefRecord): String {
        /*
         * See NFC forum specification for "Text Record Type Definition" at 3.2.1
         *
         * http://www.nfc-forum.org/specs/
         *
         * bit_7 defines encoding
         * bit_6 reserved for future use, must be 0
         * bit_5..0 length of IANA language code
         */

        val payload = record.payload

        // Get the Text Encoding

        val textEncoding = if (payload[0] and "128".toByte() == "0".toByte()) "UTF-8" else "UTF-16"

        // Get the Language Code
        val languageCodeLength = payload[0] and 51

        // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
        // e.g. "en"

        // Get the Text
        return String(payload, languageCodeLength + 1, payload.size - languageCodeLength - 1, charset(textEncoding))
    }
}