from __future__ import annotations

from pymulator.core.uds import ServiceId

from .conftest import load_handler, make_message


def test_obd2_current_data_and_supported_pids():
    session = load_handler("obd2.json")
    resp = session.response_for_message(make_message(session.arbitration_id, [ServiceId.current_powertrain_diagnostics_data, 0x0C]))
    assert resp == [0x41, 0x0C, 0x1A, 0xF8]

    supported = session.response_for_message(make_message(session.arbitration_id, [ServiceId.current_powertrain_diagnostics_data, 0x00]))
    assert supported[:2] == [0x41, 0x00]
    bitmap = int.from_bytes(bytes(supported[2:6]), "big")
    assert bitmap & (1 << (0x20 - 0x0C))


def test_obd2_dtcs_and_clear():
    session = load_handler("obd2.json")
    stored = session.response_for_message(make_message(session.arbitration_id, [ServiceId.emission_related_dtcs]))
    assert stored[:2] == [0x43, 0x01]
    assert stored[2:] == [1, 2]

    session.response_for_message(make_message(session.arbitration_id, [ServiceId.reset_emission_related_dtcs]))
    cleared = session.response_for_message(make_message(session.arbitration_id, [ServiceId.emission_related_dtcs]))
    assert cleared == [0x43, 0x00]


def test_obd2_vehicle_information():
    session = load_handler("obd2.json")
    info = session.response_for_message(make_message(session.arbitration_id, [ServiceId.vehicle_information, 0x02]))
    assert info[:2] == [0x49, 0x02]
    assert bytes(info[2:]) == bytes.fromhex("54 45 53 54 56 49 4E 31 32 33 34 35 36 37 38 39")


def test_obd2_control_operation():
    session = load_handler("obd2.json")
    resp = session.response_for_message(make_message(session.arbitration_id, [ServiceId.control_on_board_system_test_or_component, 0x01]))
    assert resp == [0x48, 0x01, 0xAA]
