import multiprocessing as mp

from ldnode.runner.config import Settings
from ldnode.runner.schemas import Worker
from .application import (
    WorkerContext,
    RecvController, 
    SendController,
    CalcController,
)


class CalculatorWorker(Worker):
    """ 计算工作进程 """            
    def check_running(self) -> bool:
        """ 检查运行状态 """
        return self.running
            
    def handle_exit(self) -> None:
        """ 处理退出 """
        self.running = False
    
    def run(self, settings: Settings, input: mp.Queue, output: mp.Queue) -> None:
        """ 运行工作进程 """
        # 创建工作进程上下文
        ctx = WorkerContext(
            running_checker=self.check_running,
            exit_handler=self.handle_exit,
        )
        # 创建控制器
        recv = RecvController(ctx, input)
        send = SendController(ctx, output)
        calc = CalcController(ctx)
        # 启动控制器
        recv.start()
        send.start()
        calc.start()
        # 等待控制器退出
        recv.join()
