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

from loguru import logger

from entity.FeedBack import recording_feedback
from enums.RecordingStatusEnum import RecordingStatus
from util.QueUtil import get_no_block_queue, put_queue, clear_queue


class RecordingHeartbeat(Thread):
    __slots__ = ('_fb_queue', '_hb_queue', '_request_id')

    def __init__(self, fb_queue, hb_queue, request_id):
        super().__init__()
        self._fb_queue = fb_queue
        self._hb_queue = hb_queue
        self._request_id = request_id

    def run(self):
        request_id = self._request_id
        hb_queue, fb_queue = self._hb_queue, self._fb_queue
        logger.info("开始启动录屏心跳线程！requestId:{}", request_id)
        hb_init_num, progress = 0, '0.0000'
        status = RecordingStatus.RECORDING_WAITING.value[0]
        try:
            while True:
                time.sleep(3)
                hb_msg = get_no_block_queue(hb_queue)
                if hb_msg is not None and len(hb_msg) > 0:
                    command_que = hb_msg.get("command")
                    progress_que = hb_msg.get("progress")
                    status_que = hb_msg.get("status")
                    if progress_que is not None:
                        progress = progress_que
                    if status_que is not None:
                        status = status_que
                    if 'stop' == command_que:
                        logger.info("开始终止心跳线程, requestId:{}", request_id)
                        break
                if hb_init_num % 30 == 0:
                    put_queue(fb_queue, recording_feedback(request_id, status, progress=progress), timeout=5, is_ex=True)
                hb_init_num += 3
        except Exception:
            logger.error("心跳线程异常:{}, requestId:{}", format_exc(), request_id)
        finally:
            clear_queue(hb_queue)
            logger.info("心跳线程停止完成！requestId:{}", request_id)
