import queue
import threading as th
import multiprocessing as mp

from ldnode import logger
from ldnode.runner.events import TaskAnswer
from .models import OutputMessageType
from .worker_context import WorkerContext


class SendController(th.Thread):
    """ 发送控制器 """
    def __init__(self, context: WorkerContext, output_channel: mp.Queue):
        super().__init__(daemon=True)
        self.context = context
        self.output_channel = output_channel
        
    def run(self) -> None:
        """ 运行控制器 """
        while self.context.running:
            try:
                msg = self.context.outbox.get(timeout=0.5)
                self.output_channel.put(msg)
            except queue.Empty:
                continue
            except Exception as e:
                logger.calculator.error(f"发送消息失败: {e}")
