package com.adealink.weparty.util

import android.graphics.Bitmap
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.log.Log
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.journeyapps.barcodescanner.BarcodeEncoder
import kotlinx.coroutines.withContext

const val TAG_QRCODE = "tag_qrcode"

const val QRCODE_WIDTH = 400
const val QRCODE_HEIGHT = 400

const val QRCODE_MARGIN = 2
suspend fun suspendGenerateQRCode(
    qrCodeText: String,
    width: Int = QRCODE_WIDTH,
    height: Int = QRCODE_HEIGHT,
    margin: Int = QRCODE_MARGIN
): Bitmap? {
    return withContext(Dispatcher.WENEXT_THREAD_POOL) {
        try {
            val barcodeEncoder = BarcodeEncoder()
            val bitmap = barcodeEncoder.encodeBitmap(
                qrCodeText,
                BarcodeFormat.QR_CODE,
                width, height,
                mapOf<EncodeHintType, Any>(
                    EncodeHintType.CHARACTER_SET to "UTF-8",
                    EncodeHintType.MARGIN to "$margin"
                )
            )
            return@withContext bitmap
        } catch (e: Exception) {
            Log.e(TAG_QRCODE, "generateQRCode fail, ${e.message}", e)
        }
        return@withContext null
    }
}