/*
 * ********************************************************************************************************************
 *
 *               iFHS7.
 *              ;BBMBMBMc                  rZMBMBR              BMB
 *              MBEr:;PBM,               7MBMMEOBB:             BBB                       RBW
 *     XK:      BO     SB.     :SZ       MBM.       c;;     ir  BBM :FFr       :SSF:    ;xBMB:r   iuGXv.    i:. iF2;
 *     DBBM0r.  :D     S7   ;XMBMB       GMBMu.     MBM:   BMB  MBMBBBMBMS   WMBMBMBBK  MBMBMBM  BMBRBMBW  .MBMBMBMBB
 *      :JMRMMD  ..    ,  1MMRM1;         ;MBMBBR:   MBM  ;MB:  BMB:   MBM. RMBr   sBMH   BM0         UMB,  BMB.  KMBv
 *     ;.   XOW  B1; :uM: 1RE,   i           .2BMBs  rMB. MBO   MBO    JMB; MBB     MBM   BBS    7MBMBOBM:  MBW   :BMc
 *     OBRJ.SEE  MRDOWOR, 3DE:7OBM       .     ;BMB   RMR7BM    BMB    MBB. BMB    ,BMR  .BBZ   MMB   rMB,  BMM   rMB7
 *     :FBRO0D0  RKXSXPR. JOKOOMPi       BMBSSWBMB;    BMBB:    MBMB0ZMBMS  .BMBOXRBMB    MBMDE RBM2;SMBM;  MBB   xBM2
 *         iZGE  O0SHSPO. uGZ7.          sBMBMBDL      :BMO     OZu:BMBK,     rRBMB0;     ,EBMB  xBMBr:ER.  RDU   :OO;
 *     ,BZ, 1D0  RPSFHXR. xWZ .SMr                  . .BBB
 *      :0BMRDG  RESSSKR. 2WOMBW;                   BMBMR
 *         i0BM: SWKHKGO  MBDv
 *           .UB  OOGDM. MK,                                          Copyright (c) 2015-2019.  斯伯坦机器人
 *              ,  XMW  ..
 *                  r                                                                     All rights reserved.
 *
 * ********************************************************************************************************************
 */

package com.sybotan.android.base.utils

import android.graphics.*
import android.webkit.JavascriptInterface
import com.google.zxing.*
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.qrcode.QRCodeReader
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import java.util.*

/**
 * 二维码生成工具
 *
 * @author  庞利祥(sybotan@126.com)
 */
object SQrCodeUtil {

    /** 背景颜色 */
    var bgColor = 0xFFFFFFFF.toInt()
    /** 前景颜色 */
    var pixelColor = 0xFF000000.toInt()

    /**
     * 创建二维码图像
     *
     * @param   contents        二维码存储的内容
     * @param   size            二维码大小
     * @return  二维码图像
     */
    @JavascriptInterface
    fun createQrCode(contents: String, size: Int, logo: Bitmap? = null): Bitmap? {
        try {
            val hints = Hashtable<EncodeHintType, Any>()
            hints[EncodeHintType.CHARACTER_SET] = "utf-8"
            hints[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.H

            val matrix = QRCodeWriter().encode(contents, BarcodeFormat.QR_CODE, size, size, hints)
            var image = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)

            for (y in 0 until size) {
                for (x in 0 until size) {
                    if (matrix.get(x, y)) {
                        image.setPixel(x, y, pixelColor)
                    } else {
                        image.setPixel(x, y, bgColor)
                    }
                }
            }

            if (null != logo) {
                image = addLogo(image, logo)
            }

            return image
        } catch (e: WriterException) {
            e.printStackTrace()
        }
        return null
    } // Function createQrCode()

    /**
     * 解析二维码图片
     *
     * @param   bitmap      二维码图片
     * @return  解析结果
     */
    fun decodeQrCode(bitmap: Bitmap): String? {
        val width = bitmap.width
        val height = bitmap.height
        val pixels = IntArray(width * height)
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
        val luminanceSource = RGBLuminanceSource(width, height, pixels)
        val binaryBitmap = BinaryBitmap(HybridBinarizer(luminanceSource))
        return decodeQrCode(binaryBitmap)
    } // Function decode()

    /**
     * 解析二维码
     *
     * @param   binaryBitmap    被解析的图形对象
     * @return  解析的结果
     */
    fun decodeQrCode(binaryBitmap: BinaryBitmap): String? {
        return try {
            val hints = HashMap<DecodeHintType, Any>()
            hints[DecodeHintType.CHARACTER_SET] = "utf-8"
            hints[DecodeHintType.TRY_HARDER] = true
            hints[DecodeHintType.POSSIBLE_FORMATS] = BarcodeFormat.QR_CODE
            val result = QRCodeReader().decode(binaryBitmap, hints)
            result.text
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    } // Function decode()

    /**
     * 为二维码图片增加Logo
     *
     * @param   src         二维码图片
     * @param   logo        Logol图片
     * @return  添加过Logo的二维码图片
     */
    private fun addLogo(src: Bitmap, logo: Bitmap): Bitmap {
        val srcWidth = src.width
        val srcHeight = src.height

        val image = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(image)
        canvas.drawBitmap(src,0f,0f, null)
        canvas.drawBitmap(logo, Rect(0, 0, srcWidth, srcHeight),
                RectF(srcWidth * 2 / 5f, srcHeight * 2 / 5f, srcWidth * 3 / 5f, srcHeight * 3 / 5f), null)

        return image
    } // Function addLogo()
} // Object QrCodeUntil