import time
from threading import Lock

import cv2
from aip import AipOcr
from loguru import logger

from enums.ExceptionEnum import ExceptionType
from exception.CustomerException import ServiceException


class OcrBaiduSdk:

    def __init__(self, content):
        self.content = content
        self.init_client()
        # self.lock = Lock()

    def init_client(self):
        self.client = AipOcr(str(self.content["baiduocr"]["APP_ID"]), self.content["baiduocr"]["API_KEY"],
                                 self.content["baiduocr"]["SECRET_KEY"])

    '''
    {
    "log_id": 2471272194,
    "words_result_num": 2,
    "words_result":
        [
            {"words": " TSINGTAO"},
            {"words": "青島睥酒"}
        ]
    }
    '''
    def universal_text_recognition(self, image, msgId):
        # try:
        #     self.lock.acquire()
        reply_num = 1
        while True:
            try:
                or_result, or_image = cv2.imencode(".jpg", image)
                res_image = self.client.basicGeneral(or_image.tobytes())
                if res_image.get("error_code") == 282403 or res_image.get("error_msg") == 'target recognize error':
                    logger.error("百度云调接口失败: {}, 当前重试次数：{}, msgId: {}", res_image, reply_num, msgId)
                    return None
                if res_image.get("error_code") is not None:
                    logger.error("百度云调接口失败: {}, 当前重试次数：{}, msgId: {}", res_image, reply_num, msgId)
                    raise Exception("百度云调接口失败")
                return res_image
            except Exception as e:
                logger.exception("通用文字识别失败: {}, 当前重试次数：{}, msgId: {}", e, reply_num, msgId)
                time.sleep(1)
                reply_num += 1
                self.init_client()
                if reply_num > 5:
                    logger.exception("通用文字识别失败: {}, msgId: {}", e, msgId)
                    raise ServiceException(ExceptionType.UNIVERSAL_TEXT_RECOGNITION_FAILED.value[0],
                                           ExceptionType.UNIVERSAL_TEXT_RECOGNITION_FAILED.value[1])
        # except Exception as ee:
        #     logger.exception("通用文字识别加锁异常: {}, msgId: {}", ee, msgId)
        #     raise ServiceException(ExceptionType.UNIVERSAL_TEXT_RECOGNITION_FAILED.value[0],
        #                            ExceptionType.UNIVERSAL_TEXT_RECOGNITION_FAILED.value[1])
        # finally:
        #     self.lock.release()
    '''
    {
        "log_id": 3583925545,
        "words_result": {
            "color": "blue",
            "number": "苏HS7766"
        }
    }
    '''
    def license_plate_recognition(self, image, msgId):
        # try:
        #     self.lock.acquire()
        reply_num = 1
        while True:
            try:
                or_result, or_image = cv2.imencode(".jpg", image)
                res_image = self.client.licensePlate(or_image.tobytes())
                if res_image.get("error_code") == 282403 or res_image.get("error_msg") == 'target recognize error':
                    logger.error("百度云调接口失败: {}, 当前重试次数：{}, msgId: {}", res_image, reply_num, msgId)
                    return None
                if res_image.get("error_code") is not None:
                    logger.error("百度云调接口失败: {}, 当前重试次数：{}, msgId: {}", res_image, reply_num, msgId)
                    raise Exception("百度云调接口失败")
                return res_image
            except Exception as e:
                logger.exception("车牌识别失败: {}, 当前重试次数：{}, msgId: {}", e, reply_num, msgId)
                time.sleep(1)
                reply_num += 1
                self.init_client()
                if reply_num > 5:
                    logger.exception("车牌识别失败: {}, msgId: {}", e, msgId)
                    raise ServiceException(ExceptionType.ABNORMAL_LICENSE_PLATE_RECOGNITION.value[0],
                                           ExceptionType.ABNORMAL_LICENSE_PLATE_RECOGNITION.value[1])
        # except Exception as ee:
        #     logger.exception("车牌识别加锁异常: {}, msgId: {}", ee, msgId)
        #     raise ServiceException(ExceptionType.ABNORMAL_LICENSE_PLATE_RECOGNITION.value[0],
        #                            ExceptionType.ABNORMAL_LICENSE_PLATE_RECOGNITION.value[1])
        # finally:
        #     self.lock.release()


