from __future__ import annotations

from pymulator.core.uds import NegativeResponseCode, ServiceId

from .conftest import load_handler, make_message


def _handle(session, payload):
    message = make_message(session.arbitration_id, payload)
    response = session.handle(message, lambda _: None)
    return None if response is None else response.bytes


def test_uds_missing_services_and_lengths():
    session = load_handler("uds.json")

    resp = _handle(session, [ServiceId.read_dtc_information, 0x01, 0xFF])
    assert resp == [0x7F, ServiceId.read_dtc_information, int(NegativeResponseCode.sub_function_not_supported)]

    resp = _handle(session, [ServiceId.read_dtc_information, 0x02])
    assert resp == [0x7F, ServiceId.read_dtc_information, int(NegativeResponseCode.incorrect_message_length_or_invalid_format)]

    resp = _handle(session, [ServiceId.read_scaling_data_by_identifier])
    assert resp == [0x7F, ServiceId.read_scaling_data_by_identifier, int(NegativeResponseCode.incorrect_message_length_or_invalid_format)]


def test_kwp_missing_services():
    session = load_handler("kwp.json")

    resp = _handle(session, [ServiceId.tester_present, 0x00])
    assert resp == [0x7F, ServiceId.tester_present, int(NegativeResponseCode.sub_function_not_supported)]


def test_obd2_missing_modes_and_pids():
    session = load_handler("obd2.json")

    resp = _handle(session, [ServiceId.control_on_board_system_test_or_component, 0x00])
    assert resp is not None

    resp = _handle(session, [ServiceId.current_powertrain_diagnostics_data, 0xFF])
    assert resp is None
