#!/usr/bin/env python
'''
@file packet_module.py

@brief Packet module base class

Copyright (C) Atmosic 2025
'''
from typing import Callable
from packet.packet_module import PacketModule
from packet.hci.hci_event_detector import HciEventDetector
from packet.hci.hci_event_factory import HciEventFactory
from packet.hci.hci_packet_implement import HciEvent
from deviceio.device_io_module import DeviceIoModule
from packet.base.packet_data_base import PacketDataBase
from error.atmosic_error import HciModuleError
from error.errorcodes import HciModuleErrorCode

class HciModule(PacketModule):
    def __init__(self, device_io_module: DeviceIoModule):
        super().__init__(device_io_module, HciEventDetector(),
                         HciEventFactory())

    def read_one(self, timeout:float = 0.0) -> HciEvent:
        packet = super().read_one(timeout)
        if not isinstance(packet, HciEvent):
            raise HciModuleError("Read packet is not HciEvent",
                                 HciModuleErrorCode.READ_PACKET_TYPE_MISMATCH)
        return packet

    def read_until(self, check_function: Callable[[HciEvent], bool],
                   timeout_s: float = 0.0) -> HciEvent:
        def check_func(packet: PacketDataBase) -> bool:
            if not isinstance(packet, HciEvent):
                return False
            return check_function(packet)
        packet = super().read_until(check_func, timeout_s)
        assert isinstance(packet, HciEvent)
        return packet
