import os

import pytest

from matterlab_relays import CE221ARelay


PORT = "/dev/ttyUSB0" if os.name == "posix" else "COM1"


@pytest.fixture
def relay_fixture(mock_serial):
    return CE221ARelay(com_port=PORT, channel=1)


def test_initialization_defaults(mock_serial, relay_fixture):
    assert isinstance(relay_fixture, CE221ARelay)
    assert relay_fixture.channel == 1
    assert relay_fixture.device._connection is mock_serial
    assert relay_fixture.on is False


def test_generate_execution_command(relay_fixture):
    assert relay_fixture._generate_execution_command(1, True).hex() == "55560000000101ad"
    assert relay_fixture._generate_execution_command(1, False).hex() == "55560000000102ae"


def test_set_relay_writes_command_and_updates_cached_state(relay_fixture, mocker):
    mocker.patch("matterlab_relays.cer221a_relay.time.sleep")
    write_spy = mocker.patch.object(relay_fixture, "write")

    relay_fixture.on = True

    write_spy.assert_called_once_with(bytes.fromhex("55560000000101ad"))
    assert relay_fixture.on is True
