import ctypes
import pytest

from pybusmonitor1553.lib1553.messages.msg_a4 import MsgA4
from pybusmonitor1553.lib1553.messages.msg_b6 import MsgB6
from pybusmonitor1553.lib1553.messages.msg_b7 import MsgB7
from pybusmonitor1553.lib1553.constants import CursorMode, DTTEnable, SAREnable


def test_msg_a4_cursor_and_sar_enable():
    m = MsgA4()

    # Default enums
    assert m.cursor_mode is not None

    # Set cursor mode to SLAVE (value 1) and verify underlying storage
    m.cursor_mode = CursorMode.SLAVE
    assert m.cursor_mode == CursorMode.SLAVE
    # Cursor mode sits in word 0; ensure data changed
    assert m.data[0] != 0

    # SAR enable test
    m.sar_enable = SAREnable.SAR_ENABLED
    assert m.sar_enable == SAREnable.SAR_ENABLED


def test_msg_b6_and_b7_basic_fields():
    b6 = MsgB6()
    b7 = MsgB7()

    # set some values and read back
    b6.target_history_tb = 2
    assert int(b6.target_history_tb) == 2

    b7.master_mode_tb = 3
    assert int(b7.master_mode_tb) == 3


def test_ppos_lat_positive_value():
    m = MsgA4()

    # construct a small positive 25-bit raw value
    raw_25 = 123456
    msw = (raw_25 >> 9) & 0xFFFF
    lsw_fragment = raw_25 & 0x1FF
    lsw_word = (lsw_fragment << 7) & 0xFFFF

    m._data[23] = msw
    m._data[24] = lsw_word

    expected = float(raw_25 * 5.9604644775e-8)
    assert pytest.approx(m.ppos_lat, rel=1e-9) == expected
