#!/usr/bin/env python

"""
Tests for zsCANfd interfaces
"""

import unittest

import can
from can.interfaces import zscanfd


class ZSCanFdTest(unittest.TestCase):
    def test_bus_creation(self):
        bus = can.Bus(channel=0, interface="zscanfd", _testing=True)
        self.assertIsInstance(bus, zscanfd.ZSCanFdBus)
        self.assertEqual(bus.protocol, can.CanProtocol.CAN_20)

        zscanfd.MockInterface.set_bitrate.assert_called()
        zscanfd.MockInterface.set_bit_timing.assert_not_called()
        zscanfd.MockInterface.set_enabled.assert_called()
        zscanfd.MockInterface.set_monitor.assert_called()
        zscanfd.MockInterface.start.assert_called()

    def test_bus_creation_bittiming(self):
        zscanfd.MockInterface.set_bitrate.reset_mock()

        bt = can.BitTiming(f_clock=24_000_000, brp=3, tseg1=13, tseg2=2, sjw=1)
        bus = can.Bus(channel=0, interface="zscanfd", timing=bt, _testing=True)

        self.assertIsInstance(bus, zscanfd.ZSCanFdBus)
        self.assertEqual(bus.protocol, can.CanProtocol.CAN_20)

        zscanfd.MockInterface.set_bitrate.assert_not_called()
        zscanfd.MockInterface.set_bit_timing.assert_called()
        zscanfd.MockInterface.set_enabled.assert_called()
        zscanfd.MockInterface.set_monitor.assert_called()
        zscanfd.MockInterface.start.assert_called()

    def test_transmit(self):
        bus = can.Bus(channel=0, interface="zscanfd", _testing=True)
        msg = can.Message(
            arbitration_id=0xC0FFEF, data=[1, 2, 3, 4, 5, 6, 7, 8], is_extended_id=True
        )
        bus.send(msg)
        zscanfd.MockInterface.send.assert_called()

    def test_recv(self):
        bus = can.Bus(channel=0, interface="zscanfd", _testing=True)
        frame = bus.recv(timeout=0.5)
        zscanfd.MockInterface.recv.assert_called()
        self.assertIsInstance(frame, can.Message)

    def test_recv_timeout(self):
        bus = can.Bus(channel=0, interface="zscanfd", _testing=True)
        frame = bus.recv(timeout=0.0)
        zscanfd.MockInterface.recv.assert_called()
        self.assertIsNone(frame)

    def test_shutdown(self):
        bus = can.Bus(channel=0, interface="zscanfd", _testing=True)
        bus.shutdown()
        zscanfd.MockInterface.stop.assert_called()
