package com.duolebo.blyrobot.tools

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.util.Log
import com.baidu.aip.ocr.AipOcr
import java.io.File


class OcrManager {
    companion object {
        @SuppressLint("StaticFieldLeak")
        val instance = OcrManager()
        val TAG = "RobotOcrManager"
        const val AK = "zy4gq9vvYa0UF133COi2ITHI"
        const val SK = "cGG1wblcyMfpKjo8bG68lZYeysrEVOFq"

        const val APP_ID = "11067709"
        const val API_KEY = "APMf6m40GKnZK74ArXYmdMCf"
        const val SECRET_KEY = "KfiA2R9BTWo5xN4R9gHeztMQ6h3seyZL"

        const val CONN_TIMEOUT = 2000
        const val SOCKET_TIMEOUT = 60000
    }

    private lateinit var context: Context
    private lateinit var aipOcr: AipOcr

    fun init(context: Context) {
        this.context = context
        initOcr()
    }

    //  初始化百度ocr调用
    private fun initOcr() {
        this.aipOcr = AipOcr(APP_ID, API_KEY, SECRET_KEY)
        aipOcr.setConnectionTimeoutInMillis(CONN_TIMEOUT)
        aipOcr.setSocketTimeoutInMillis(SOCKET_TIMEOUT)
    }

    fun imageOcr(filePath: String) : String {
        var res = ""
        try {
            val options = HashMap<String, String>()
            options["recognize_granularity"] = "big"
            options["detect_direction"] = "true"

            // 先用简单识别，每天有5w次免费额度
            var result = aipOcr.basicGeneral(filePath, options)
            res = getOcrWords(result)

            // 如果无法识别，调用高精度识别，每天500次额度
            if (!TextUtils.isDigitsOnly(res)) {
                result = aipOcr.basicAccurateGeneral(filePath, options)
                res = getOcrWords(result)
            }

            Log.i(TAG, "imageOrc: $res")
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return res
    }

    private fun getOcrWords(result: org.json.JSONObject): String {
        var words = ""
        val wordsResult = result.getJSONArray("words_result")
        val num = result.getInt("words_result_num")
        if (wordsResult != null && num > 0) {
            val wordsObject = wordsResult.getJSONObject(0)
            words = wordsObject.getString("words")
            words = words.replace("-", "")
        }

        return words
    }

    interface OcrListener {
        fun onResult(result: String)
    }

}