package ch.threema.app.qrcodes

import android.graphics.Bitmap
import ch.threema.testhelpers.loadResource
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull

class QrCodeGeneratorTest {

    @Test
    fun generateQrCode() {
        val bitmap = QrCodeGenerator().generateWithUnicodeSupport(content = "äbc-123 \uD83D\uDC08")
        assertNotNull(bitmap)

        try {
            assertEquals(
                loadResource("qr-code.txt"),
                bitmap.toPixelString(),
            )
        } finally {
            bitmap.recycle()
        }
    }

    private fun Bitmap.toPixelString(): String {
        val pixels = IntArray(width * height)
        getPixels(pixels, 0, width, 0, 0, width, height)
        return pixels.toList()
            .chunked(width)
            .joinToString(separator = "\n") { pixelRow ->
                pixelRow.joinToString(separator = "") { pixelColor ->
                    when (pixelColor) {
                        BLACK -> "■"
                        WHITE -> " "
                        else -> "?"
                    }
                }
            }
    }

    companion object {
        private const val BLACK = 0xFF000000.toInt()
        private const val WHITE = 0xFFFFFFFF.toInt()
    }
}
