"""
Interface for zsCANfd devices from Zilogic
"""

import logging
import time
from typing import Any, Optional, Union
from unittest.mock import Mock

from can import BitTiming, BitTimingFd, BusABC, CanProtocol, Message

from ..exceptions import (
    CanInitializationError,
    CanInterfaceNotImplementedError,
    error_check,
)
from ..util import check_or_adjust_timing_clock, deprecated_args_alias

logger = logging.getLogger(__name__)

try:
    import zscanfd
except ImportError:
    zscanfd = None
    logger.warning(
        "The zscanfd module is not installed. Install it using `pip install zscanfd`"
    )


class ZSCanFdBus(BusABC):
    """ZSCanFd interface"""
    # Class attribute
    zscanfd_interface_ref = None
    zscanfd_interface_status : bool = True

    @classmethod
    def set_zscanfd_interface_status(cls, status, zscanfd_obj):
        cls.zscanfd_interface_status = status
        cls.zscanfd_interface_ref = zscanfd_obj

    @classmethod
    def get_zscanfd_interface_ref(cls):
        return cls.zscanfd_interface_ref

    @classmethod
    def get_zscanfd_interface_status(cls):
        return cls.zscanfd_interface_status

    @staticmethod
    def _detect_available_configs():
        try:
            interface = zscanfd.Interface()
        except (NameError, SystemError, AttributeError):
            logger.debug(
                "Could not import or instantiate zscanfd, so no configurations are available"
            )
            return []

        channels = []
        for i in range(0, interface.channel_count()):
            channels.append({"interface": "zscanfd", "channel": f"ch:{i}"})
        return channels

    @deprecated_args_alias(
        deprecation_start="4.2.0", deprecation_end="5.0.0", bit_timing="timing"
    )
    def __init__(
        self,
        channel: int,
        bitrate: int = 500_000,
        poll_interval: float = 0.01,
        monitor: bool = False,
        timing: Optional[Union[BitTiming, BitTimingFd]] = None,
        fd: bool = False,
        data_bitrate: int = 2_000_000,
        dev_ser_num: str = "",
        **kwargs: Any,
    ) -> None:
        """
        :param int channel:
            Channel number (zero indexed, labeled on multi-channel devices)
        :param int bitrate:
            Bitrate in bits/s
        :param bool monitor:
            If true, operate in listen-only monitoring mode
        :param timing:
            Optional :class:`~can.BitTiming` instance to use for custom bit timing setting.
            If this argument is set then it overrides the bitrate argument. The
            `f_clock` value of the timing instance must be set to 24_000_000 (24MHz)
            for standard CAN.
            CAN FD and the :class:`~can.BitTimingFd` class are not supported.
        :param bool fd:
            Enables CAN-FD usage.
        :param int data_bitrate:
            Data bitrate in bit/s (only if CAN-Fd is enabled).
        """

        if kwargs.get("_testing", False):
            self.interface = MockInterface()
        else:
            if zscanfd is None:
                raise CanInterfaceNotImplementedError(
                    "The zscanfd module is not installed. "
                    "Install it using `python -m pip install zscanfd`"
                )
            with error_check(
                "Cannot create the zscanfd.Interface", CanInitializationError
            ):
                if self.get_zscanfd_interface_status():
                    """
                    Create a zscanfd.Interface with the device serial number if `dev_ser_num` is not empty.
                    Otherwise, create a zscanfd.Interface without a device serial number.
                    """
                    self.interface = zscanfd.Interface(dev_ser_num) if dev_ser_num != "" else zscanfd.Interface()
                    self.set_zscanfd_interface_status(False, self.interface)
                else:
                    self.interface = self.get_zscanfd_interface_ref()

        self.channel = int(channel)
        self.channel_info = f"zsCANfd: ch:{channel}"
        self._can_protocol = CanProtocol.CAN_20

        # Configure the interface
        with error_check("Cannot setup the zscanfd.Interface", CanInitializationError):
            if isinstance(timing, BitTiming):
                timing = check_or_adjust_timing_clock(timing, valid_clocks=[24_000_000])

                # use custom bit timing
                self.interface.set_bit_timing(
                    int(channel),
                    int(timing.brp),
                    int(timing.tseg1),
                    int(timing.tseg2),
                    int(timing.sjw),
                )
            elif isinstance(timing, BitTimingFd) and fd:
                self.interface.set_bit_timing(
                    int(channel),
                    int(timing.nom_brp),
                    int(timing.nom_tseg1),
                    int(timing.nom_tseg2),
                    int(timing.nom_sjw),
                )
                self.interface.set_data_bit_timing(
                    int(channel),
                    int(timing.data_brp),
                    int(timing.data_tseg1),
                    int(timing.data_tseg2),
                    int(timing.data_sjw),
                )
            else:
                # use bitrate
                self.interface.set_bitrate(int(channel), int(bitrate))
                if fd:
                    # Set the FD support using zscanfd driver
                    self.interface.set_fd(int(channel), fd)
                    self.interface.set_data_bitrate(int(channel), int(data_bitrate))

            self.interface.set_enabled(int(channel), True)
            self.interface.set_monitor(int(channel), monitor)
            self.interface.start(int(channel))

        super().__init__(
            channel=channel,
            bitrate=bitrate,
            poll_interval=poll_interval,
            **kwargs,
        )

    def _recv_internal(self, timeout):
        with error_check("Cannot receive message"):
            frame = self.interface.recv(int(timeout * 1000), self.channel)
        if frame is None:
            # timeout occurred
            return None, False

        msg = Message(
            arbitration_id=frame["id"],
            is_extended_id=frame["extended"],
            timestamp=frame["hw_timestamp"] if frame["hw_timestamp"] != 0 else frame["sw_timestamp"],
            is_remote_frame=frame["rtr"],
            dlc=len(frame["data"]),
            data=frame["data"],
            channel=frame["channel"],
            is_rx=(not frame["loopback"]),  # received if not loopback frame
        )
        return msg, False

    def send(self, msg, timeout=None):
        with error_check("Cannot send message"):
            if msg.is_fd:
                self.interface.send_fd(
                    self.channel,
                    msg.arbitration_id,
                    bool(msg.is_extended_id),
                    bool(msg.is_remote_frame),
                    bool(msg.is_fd),
                    bool(msg.bitrate_switch),
                    msg.dlc,
                    msg.data,
                )
            else:
                self.interface.send(
                    self.channel,
                    msg.arbitration_id,
                    bool(msg.is_extended_id),
                    bool(msg.is_remote_frame),
                    msg.dlc,
                    msg.data,
                )

    def shutdown(self):
        super().shutdown()
        with error_check("Cannot shutdown interface"):
            self.interface.stop(self.channel)
            self.interface.set_enabled(int(self.channel), False)

def mock_recv(timeout):
    if timeout > 0:
        return {
            "id": 0x123,
            "extended": False,
            "timestamp": time.time(),
            "loopback": False,
            "rtr": False,
            "dlc": 8,
            "data": [1, 2, 3, 4, 5, 6, 7, 8],
            "channel": 0,
        }
    else:
        # simulate timeout when timeout = 0
        return None


class MockInterface:
    """
    Mock interface to replace real interface when testing.
    This allows for tests to run without actual hardware.
    """

    start = Mock()
    set_bitrate = Mock()
    set_data_bitrate = Mock()
    set_bit_timing = Mock()
    set_data_bit_timing = Mock()
    set_enabled = Mock()
    set_monitor = Mock()
    stop = Mock()
    send = Mock()
    send_fd = Mock()
    set_fd = Mock()
    channel_count = Mock(return_value=1)

    recv = Mock(side_effect=mock_recv)
