import pytest

from webui import server


def test_input_method_defaults_to_usb(tmp_path):
    assert server.readInputMethod(tmp_path) == 'usb'


def test_input_method_roundtrip(tmp_path):
    server.writeInputMethod('mac_bt', tmp_path)

    assert server.readInputMethod(tmp_path) == 'mac_bt'


def test_input_method_rejects_unknown(tmp_path):
    with pytest.raises(ValueError):
        server.writeInputMethod('quatsch', tmp_path)


def test_input_method_falls_back_on_garbage(tmp_path):
    (tmp_path / '.input-method').write_text('bluetooth', encoding='ascii')

    assert server.readInputMethod(tmp_path) == 'usb'


def test_build_hardware_lists_displays(mocker):
    mocker.patch('src.utils.display.getDisplays', return_value=[
        {'device': '\\\\.\\DISPLAY1', 'label': 'Bildschirm 1 — 2560×1440'},
        {'device': '\\\\.\\DISPLAY3', 'label': 'Bildschirm 3 — Virtuell'},
    ])
    mocker.patch('src.utils.display.getSelectedDisplay',
                 return_value={'device': '\\\\.\\DISPLAY3'})

    hardware = server.buildHardware()

    assert len(hardware['displays']) == 2
    assert hardware['selected'] == '\\\\.\\DISPLAY3'
    assert hardware['error'] is None


def test_build_hardware_survives_display_error(mocker):
    mocker.patch('src.utils.display.getDisplays',
                 side_effect=RuntimeError('kein Bildschirm'))

    hardware = server.buildHardware()

    assert hardware['displays'] == []
    assert hardware['error'] == 'kein Bildschirm'
