from __future__ import annotations

from pymulator.core.uds import ServiceId

from .conftest import load_handler, make_message


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

    ecu_resp = session.handle_request(make_message(session.arbitration_id, [ServiceId.kwp_read_ecu_identification, 0x90]))
    assert ecu_resp == [0x5A, 0x90, 0x54, 0x45, 0x53, 0x54]

    local_resp = session.handle_request(make_message(session.arbitration_id, [ServiceId.kwp_read_data_by_local_identifier, 0x01]))
    assert local_resp == [0x61, 0x01, 0xAA, 0xBB]

    common_resp = session.handle_request(make_message(session.arbitration_id, [ServiceId.read_data_by_identifier, 0xF1, 0x87]))
    assert common_resp == [0x62, 0xF1, 0x87, 0x10, 0x11]


def test_kwp_dtc_status_report():
    session = load_handler("kwp.json")
    dtc_resp = session.handle_request(
        make_message(session.arbitration_id, [ServiceId.kwp_read_dtcs_by_status, 0x02, 0xFF, 0xFF])
    )
    assert dtc_resp == [0x58, 0x01, 1, 2, 3]


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

    freeze = session.handle_request(make_message(session.arbitration_id, [ServiceId.kwp_read_freeze_frame_data]))
    assert freeze == [0x52]

    dtcs = session.handle_request(make_message(session.arbitration_id, [ServiceId.kwp_read_diagnostic_trouble_code]))
    assert dtcs == [0x53, 0x01, 1, 2, 3]

    status = session.handle_request(make_message(session.arbitration_id, [ServiceId.kwp_read_status_of_dtcs, 0xFF]))
    assert status == [0x57, 0x08, 1, 2, 3, 0x08]

    scaling = session.handle_request(make_message(session.arbitration_id, [ServiceId.read_scaling_data_by_identifier, 0xF1, 0x87]))
    assert scaling == [0x64, 0xF1, 0x87, 0x10, 0x11]

    stop = session.handle_request(make_message(session.arbitration_id, [ServiceId.kwp_stop_diagnostic_session]))
    assert stop == [0x60]

    start_comm = session.handle_request(make_message(session.arbitration_id, [ServiceId.kwp_start_communication, 0x12, 0x34]))
    assert start_comm == [0xC1, 0x12, 0x34]

    stop_comm = session.handle_request(make_message(session.arbitration_id, [ServiceId.kwp_stop_communication]))
    assert stop_comm == [0xC2]

    timing_read = session.handle_request(make_message(session.arbitration_id, [ServiceId.kwp_access_timing_parameters, 0x01]))
    assert timing_read == [0xC3, 0x01, 0x00, 0x00, 0x00]

    timing_set = session.handle_request(
        make_message(session.arbitration_id, [ServiceId.kwp_access_timing_parameters, 0x02, 0x12, 0x34, 0x56])
    )
    assert timing_set == [0xC3, 0x02]

    timing_read_updated = session.handle_request(make_message(session.arbitration_id, [ServiceId.kwp_access_timing_parameters, 0x01]))
    assert timing_read_updated == [0xC3, 0x01, 0x12, 0x34, 0x56]

    network = session.handle_request(make_message(session.arbitration_id, [ServiceId.kwp_network_configuration, 0xAA]))
    assert network == [0xC4, 0xAA]
