# -*- coding: utf-8 -*-
from time import time
from traceback import format_exc

from loguru import logger

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


def get_no_block_queue(queue):
    try:
        return queue.get(block=False)
    except Exception:
        return None


def put_queue(queue, result, block=True, timeout=None, is_ex=False):
    try:
        queue.put(result, block=block, timeout=timeout)
    except Exception:
        logger.error("添加队列异常：{}", format_exc())
        if is_ex:
            raise ServiceException(ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
                                   ExceptionType.SERVICE_INNER_EXCEPTION.value[1])


def put_queue_result(queue, result, block=True, timeout=None):
    try:
        queue.put(result, block=block, timeout=timeout)
        return True
    except Exception:
        logger.error("添加队列异常：{}", format_exc())
        return False


def clear_queue(queue):
    c_time = time()
    while True:
        if time() - c_time > 120:
            logger.error("清空队列失败, 情况队列超时！")
            raise ServiceException(ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
                                   ExceptionType.SERVICE_INNER_EXCEPTION.value[1])
        get_no_block_queue(queue)
        if queue.empty() or queue.qsize() == 0:
            break
        # try:
        #     queue.get_nowait()
        # except Exception:
        #     break
