package de.softwareapp_hb.privateqrscanner.util

import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test

class BarcodePayloadTest {

    @Test
    fun readablePayload_prefersDisplayableRawValue() {
        val payload = readablePayload(
            rawValue = "  hello world  ",
            displayValue = null,
            rawBytes = null
        )

        assertEquals("hello world", payload?.content)
        assertFalse(payload?.isBase64Encoded ?: true)
    }

    @Test
    fun readablePayload_keepsDisplayableUtf8Bytes() {
        val text = "Ticket \uD83D\uDE00"

        val payload = readablePayload(
            rawValue = null,
            displayValue = null,
            rawBytes = text.toByteArray(Charsets.UTF_8)
        )

        assertEquals(text, payload?.content)
        assertFalse(payload?.isBase64Encoded ?: true)
    }

    @Test
    fun readablePayload_base64EncodesBinaryBytes() {
        val payload = readablePayload(
            rawValue = null,
            displayValue = null,
            rawBytes = byteArrayOf(0x00, 0x01, 0x02, 0x03, 0xFF.toByte())
        )

        assertEquals("AAECA/8=", payload?.content)
        assertTrue(payload?.isBase64Encoded ?: false)
    }

    @Test
    fun readablePayload_base64EncodesRawBytesWhenRawValueContainsReplacementCharacter() {
        val payload = readablePayload(
            rawValue = "broken \uFFFD",
            displayValue = null,
            rawBytes = byteArrayOf(0x00, 0x01, 0x02)
        )

        assertEquals("AAEC", payload?.content)
        assertTrue(payload?.isBase64Encoded ?: false)
    }

    @Test
    fun readablePayload_base64EncodesRawValueWhenNoBytesAreAvailable() {
        val payload = readablePayload(
            rawValue = "A\u0000B",
            displayValue = null,
            rawBytes = null
        )

        assertEquals("QQBC", payload?.content)
        assertTrue(payload?.isBase64Encoded ?: false)
    }
}
